【发布时间】:2012-02-11 12:41:57
【问题描述】:
我可以在单个语句中插入项目,但我想要做的是使用存储过程的另一个版本。我怎么做。这是我的代码:
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 注入、企业库数据块(如果您愿意,可以帮助您处理数据访问层的库)进行大量研究,然后我认为您可以做对。我可以回答你的问题,但我更愿意真正帮助你告诉你要学习的东西。
-
附带说明:您应该为您的 SQL 插入使用 参数化查询 - 您不应该只是将您的 SQL 语句连接在一起 - 这为 SQL 注入攻击打开了大门. See how to do parametrized queries here
标签: c# sql-server-2008 stored-procedures