[英]How to insert the result of the select query in another table's column
[英]Result of a Select query into another table
在Windows窗体应用程序中,我想将“选择SQL查询的结果”添加到另一个表中。
点击按钮后面的代码,我认为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(); }
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:还将括号放在select语句之前
注意:确保textBox1.Text不为null或为空,还应该使用参数化查询
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.