将数组列表的值插入数据库

本文关键字:插入 数据库 数组 列表 | 更新日期: 2023-09-27 18:15:28

我在我的项目中使用了一个复选框列表。我使用下面的代码将所有复选项值存储在arraylist中

 ArrayList  services= new ArrayList();
for (int i = 0; i < chkservices.Items.Count; i++)
        {
            if (chkservices.Items[i].Selected == true)
            {
                services.Add(chkservices.Items[i].Text+',');
            }
        }

现在的问题是,当我插入数据到数据库中,而不是在数组列表中的数据,它被插入为'System.Collections。ArrayList'我如何在单个插入语句中插入所有值到数据库中?

编辑

插入数据库

con.Open();
        SqlCommand cmd = new SqlCommand("insert into XXX(First_Name,Last_Name,ServicesProvided) values ('" + txtfrstname.Text + "','" + txtlastname.Text + "','" + services + "')", con);
        cmd.ExecuteNonQuery();
        con.Close();
我需要保存复选框中的复选项,并将其保存在数据库 中。
it should be saved in database as
  First_Name             Last_name                 ServicesProvided
user1firstname        user1lastname               selectedvalue1,
                                              selectedvalue2,selectedvalue3

将数组列表的值插入数据库

为什么不用下面的代码来连接你的数据呢?

 var mydata = String.Join(',', chkservices.Items
   .Where( a => a.Selected).Select( b => b.Text));

所以你可以添加你的数据作为一个字符串。

编辑:

将字符串连接起来进行查询是一个非常糟糕的习惯!除了很多副作用,比如你的情况,这是一个严重的安全漏洞。请尝试使用参数化查询:

     SqlCommand cmd = new SqlCommand(
         @"insert into XXX(First_Name,Last_Name,ServicesProvided) values 
         (@First_Name,@Last_Name,@ServicesProvided")", con); 
      cmd.Parameters.AddWithValue("@ServicesProvided", mydata);
      cmd.Parameters.AddWithValue("@First_Name", frstname.Text);
      cmd.Parameters.AddWithValue("@Last_Name", txtlastname.Text);
    cmd.ExecuteNonQuery();

mydata是我第一个例子中的变量。

您需要获取数组列表的值并逐个发送

或创建一个存储过程,将所有值发送到使用alexander Galkins示例的存储过程(或使用a Aggregate方法)。然后使用split函数拆分字符串并插入所有记录

使用INSERT INTO语句一次只能插入一行,除非你使用子查询从其他表中选择数据。

由于数据库中没有数据,您唯一的选择是遍历数组并将每个值作为新行插入。

不要使用ArrayList,你有你需要的泛型列表:

List<string> services = new List<string>();
for (int i = 0; i < chkservices.Items.Count; i++)
{
    if (chkservices.Items[i].Selected == true)
    {
        services.Add(chkservices.Items[i].Text);
    }
}
//...connection stuff....
strSQL = "INSERT INTO MyTable (MyField) VALUES (@val)"
using (SqlCommand command = new SqlCommand(strSQL, connection))
{
    command.Parameters.AddWithValue("@val", "");
    foreach (string service in services)
    {
        command.Parameters["@val"].Value = service;
        command.ExecuteNonQuery();
    }
}

你有多少个复选框?如果你只有一个小复选框,那么我建议你将它们的每个状态转换成代表一个数字的位掩码,然后将其存储到数据库中。

long bitMask = 0; // All uncheck
for (int i = 0; i < chkServices.Items.Count; ++i) {
    if (chkServices.Items[i].Checked) {
        bitMask |= (1 << i);
    }
}
// Store bitMask to Database

在后面,你可以在需要的时候再次通过bitMask获取状态