SQL查询未在C#中执行

时间:2013-12-08 22:43:17

标签: c# sql

我有一个SQL查询,我想在单击按钮时在C#中执行它,但是当我单击时 按钮数据库不受影响:

private void button1_Click(object sender, EventArgs e) {
    String ConnectionString = "Data Source=localhost;Initial Catalog=mydb;Integrated Security=True";
    SqlConnection con = new SqlConnection(ConnectionString);
    SqlCommand cmd = new SqlCommand();
    con.Open();
    cmd.CommandText = "INSERT INTO MedTab (MedID,MedName,Manf,MedProd,MedExp,TimeLeft,InStock) VALUES (4,'sdfs','sdfsd','sdfsdf','sdfsdf','sdfsd',33);";
    con.Close();
}

3 个答案:

答案 0 :(得分:1)

您想要的代码是:

String ConnectionString = "Data Source=localhost;Initial Catalog=mydb;Integrated Security=True";
String sql = "INSERT INTO MedTab (MedID,MedName,Manf,MedProd,MedExp,TimeLeft,InStock) VALUES (4,'sdfs','sdfsd','sdfsdf','sdfsdf','sdfsd',33);";

using (SqlConnection con = new SqlConnection(ConnectionString))
{
  con.Open();

  using (SqlCommand cmd = new SqlCommand(sql, con))
    cmd.ExecuteNonQuery();
}

答案 1 :(得分:0)

在设置命令文本后添加cmd.ExecuteNonQuery

答案 2 :(得分:0)

您需要实际执行查询(尝试ExecuteNonQuery)。

您当前正在打开连接,将语句设置为执行,然后关闭连接。