简体   繁体   English

选择查询到另一个表的结果

[英]Result of a Select query into another table

In Windows form application, I want to add The Result of a Select SQL Query into another table. 在Windows窗体应用程序中,我想将“选择SQL查询的结果”添加到另一个表中。

  • The input pid (textBox1.text) is a integer no. 输入pid(textBox1.text)是整数。
  • When running this application, I am getting the message "Product Added" but actually its not. 运行此应用程序时,我收到消息“已添加产品”,但实际上没有。
  • This the code behind the button click, I think the SQL query is wrong somewhere. 点击按钮后面的代码,我认为SQL查询在某处是错误的。 please help 请帮忙

      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");

  }

You made following mistakes in your code 您在代码中犯了以下错误

1 : you open connection before creating of sqlcommand object 1:在创建sqlcommand对象之前打开连接

2: you did not write code to execute the query properly 2:您没有编写代码来正确执行查询

3: you also put parenthesis before the select statement 3:还将括号放在select语句之前

Note: Make Sure textBox1.Text is not null or empty also you should use paramterize query 注意:确保textBox1.Text不为null或为空,还应该使用参数化查询

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM