C# SQL查询未在C中执行#
我有一个SQL查询,我想在点击按钮时用C#执行它,但是当我点击 按钮数据库不受影响:C# SQL查询未在C中执行#,c#,sql,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(Connect
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();
}
在设置命令文本后添加
cmd.ExecuteNonQuery
。在设置命令文本后添加cmd.ExecuteNonQuery
。您需要实际执行查询(尝试ExecuteNonQuery
)
您当前正在打开一个连接,将语句设置为执行,然后刚刚关闭连接。您需要实际执行查询(请尝试
ExecuteNonQuery
)
您当前正在打开连接,将语句设置为执行,然后关闭连接。您需要的代码如下:
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();
}
您需要的代码如下:
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();
}
命令在何处执行?命令在何处执行?如果在SqlConnection中添加using,则连接将在ExecuteOnQuery之后自动关闭。如果在SqlConnection中添加using,则连接将在ExecuteOnQuery之后自动关闭。