2017-08-14 136 views
0

我正在尝试在C#中为Postgre创建参数化的commad。我的目标是将字符串列表写入数据库表。C#的Postgre SQL参数化查询#

List<string> list = new List<string> { "listItem1", "listItem2", "listItem3" }; 
command.CommandText = "INSERT INTO table (item) VALUES (@ListItem);"; 
foreach (var item in list) 
    { 
    command.Parameters.AddWithValue("ListItem", item); 
    command.ExecuteNonQuery(); 
    } 

这段代码将用3次写入db表的listItem1完成。我想我需要将Paramater的名字与价值分开,但我不知道如何。有人可以帮忙吗?谢谢。

+0

'AddWithValue'增加了对*每次迭代*新* *参数:刚刚一次你应该声明参数。 –

+0

您需要将参数添加到foreach循环外部的命令中,作为cmd.Parameters.Add(“@ ListItem”,SqlDbType.NVarchar);并将其值设置为循环内部的command.Parameters [“@ItemItem”]。价值=项目;' –

回答

0

AddWithValue增加了对每个迭代 parapeter。

List<string> list = new List<string> { 
    "listItem1", "listItem2", "listItem3" }; 

command.CommandText = "INSERT INTO table (item) VALUES (@ListItem);"; 

// Declare parameter once ... 
//TODO: specify parameter's value type as a second argument 
command.Parameters.Add("@ListItem"); 

foreach (var item in list) { 
    // ...use many 
    command.Parameters[0].Value = item; 
    command.ExecuteNonQuery(); 
} 
+0

感谢它的帮助。新参数的定义需要数据类型说明。 'command.Parameters.Add(“@ Produkt”,NpgsqlTypes.NpgsqlDbType.Varchar);' –