简体   繁体   English

将列表框项目插入SQL数据库表,同时保持“身份”列不变

[英]Insert Listbox Items to SQL Database table while keeping Identity column constant

I have the following code. 我有以下代码。

SqlConnection connection = new SqlConnection(@"Data Source = WOOLSVALLEG\MEGASUL; Initial Catalog = POSListDB2; Integrated Security = True");
for (int k = 0; k < listBox1.Items.Count; k++)
{
    SqlCommand command = new SqlCommand("INSERT INTO POStable2(L"+k+") Values(@L"+k+")", connection);
    command.CommandType = CommandType.Text;
    command.Connection = connection;
    command.Parameters.Clear();
    command.Parameters.AddWithValue("@L" + k +"", listBox1.Items[k].ToString());
    connection.Open();
    command.ExecuteNonQuery();
    connection.Close();
}

I want to insert each time an item of listbox into column of database table. 我想每次将列表框的项目插入数据库表的列中。 I need identity column too. 我也需要身份列。 But the problem is it adds data diagonally as it updates each the loop iterate. 但是问题是它在对每个循环进行更新时会斜向添加数据。 How I can add for example 5 items from listbox into 5 columns of database table while the identity column remain same for the loop operation. 我如何将列表框中的5个项目添加到数据库表的5列中,而对于循环操作,identity列保持不变。 Thanks 谢谢

this is what I got; 这就是我得到的;

在此处输入图片说明

You need to build a single insert statement and execute it only once. 您只需要构建一个插入语句并仅执行一次即可。 One way to do it is like this: 一种方法是这样的:

SqlCommand command = new SqlCommand();
command.CommandType = CommandType.Text;
command.Connection = connection;
command.Parameters.Clear();
var sql = "INSERT INTO POStable2(";
var values = "Values(";
for (int k = 0; k < listBox1.Items.Count; k++)
{
    sql = sql + "L" + k + ",";
    values = values + "@L" + k + ",";
    command.Parameters.AddWithValue("@L" + k +"", listBox1.Items[k].ToString());

}
sql = sql.TrimEnd(",") + ") " + values.TrimEnd(",") + ") ";
command.CommandText = sql;
connection.Open();
command.ExecuteNonQuery();
connection.Close();

I didn't test it, of course. 我当然没有测试。 You might want to put a brakepoint before opening the connection and check the sql you get. 您可能需要在打开连接之前检查刹车点,然后检查获得的sql。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM