我可以在单个语句中插入项目,但我想要做的是使用存储过程的另一个版本。我怎么做。这里是我的代码:如何使用存储过程在SQL中插入多行?
private void button1_Click(object sender, EventArgs e)
{
#region Get Values
string[] array = {textBox1.Text+":"+textBox5.Text,textBox2.Text+":"+textBox6.Text,textBox3.Text+":"+textBox7.Text,textBox4.Text+":"+textBox8.Text};
string query = "";
string product = "";
int qty = 0;
for (int i = 0; i < array.Length; i++)
{
product = array[i].ToString().Substring(0,array[i].ToString().IndexOf(':'));
qty = int.Parse(array[i].ToString().Substring(array[i].ToString().IndexOf(':')+1));
if (string.IsNullOrEmpty(query))
{
query = "Insert Into MySampleTable Values ('"+product+"','"+qty+"')";
}
else
{
query += ",('" + product + "','" + qty + "')";
}
}
#endregion
string connect = "Data Source=RANDEL-PC;Initial Catalog=Randel;Integrated Security=True";
SqlConnection connection = new SqlConnection(connect);
connection.Open();
string insert = query;
SqlCommand command = new SqlCommand(query,connection);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
connection.Dispose();
label5.Visible = true;
label5.Text = insert;
}
}
先生/女士,您的答案会有很大的帮助,非常感谢。谢谢++
有这么多的事情是错误的。我认为你需要研究很多关于数据访问层,防止sql注入,企业库数据块(如果你愿意,可以用你的数据访问层来帮助你),之后我认为你可以做到这一点。我可以回答你的问题,但我更愿意帮你告诉你要学习的东西。 – 2012-02-11 12:52:48
作为一个侧面提示:您应该为您的SQL插入使用**参数化查询** - 您不应该只是将您的SQL语句连接在一起 - 这会打开SQL注入攻击的大门。 [请参见此处如何执行参数化查询](http://www.4guysfromrolla.com/webtech/092601-1.shtml) – 2012-02-11 12:53:05