executenonquery()
错误C#
这就是我的代码的样子
con.Open();
String name = textBox1.Text.ToString();
String address = textBox2.Text.ToString();
String id = textBox3.Text.ToString();
int iid = Int32.Parse(id);
String semester = textBox4.Text.ToString();
int i_sem = Int32.Parse(semester);
String field = comboBox1.SelectedItem.ToString();
String qry = "insert into Table values('" + name + "','" + address + "'," + iid + "," + i_sem + ",'" + field + "',)";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.ExecuteNonQuery();
executenonquery()
总是让我出问题!
int i = cmd.ExecuteNonQuery();
答案 0 :(得分:1)
您需要修复几件事:
,
。SqlParameterCollection.AddWithValue(String, Object)
方法获得相同的结果,并避免 SQL注入:command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT into YourTableName (name, address, id, semester, field) VALUES (@name, @address, @id, @semester, @field)";
command.Parameters.AddWithValue("@name", name);
command.Parameters.AddWithValue("@address", address);
command.Parameters.AddWithValue("@id", iid);
command.Parameters.AddWithValue("@semester", i_sem);
command.Parameters.AddWithValue("@field", field);
try
{
connection.Open();
int recordsAffected = command.ExecuteNonQuery();
}
catch(SqlException)
{
// error here
}
finally
{
connection.Close(); //close your connection if you do not need to keep it open
}
更多信息: