在Windows窗体应用程序中,我想将Select SQL Query的结果添加到另一个表中。
这个按钮点击后面的代码,我认为SQL查询在某处是错误的。请帮忙
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=HOME;Initial
Catalog=Test;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("insert into list (pname, pprice)
(select pname, pprice from products where pid='" +textBox1.Text+"')", con);
MessageBox.Show("Product Added");
con.Close();
}
答案 0 :(得分:1)
private void button1_Click(object sender, EventArgs e)
{
SqlDataAdapter SDA = new SqlDataAdapter();
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection("Data Source=HOME;Initial
Catalog=Test;Integrated Security=True");
SqlCommand cmd = new SqlCommand("insert into list (pname, pprice)
select pname, pprice from products where pid='" +textBox1.Text+"'", con);
con.Open();
SDA.SelectCommand = cmd;
SDA.Fill(dt);
con.Close();
MessageBox.Show("Product Added");
}
您在代码中犯了以下错误
1:在创建sqlcommand对象之前打开连接
2:你没有编写代码来正确执行查询
3:你还在括号
之前加上括号
注意:强> 确保textBox1.Text不为null或为空也应该使用参数化查询