我有一个错误,您必须声明一个静态变量@campus_id。我不知道如何声明和声明声明以及声明静态变量意味着什么。请帮帮我!
private void btnSave_Click(object sender, EventArgs e)
{
try
{
CS = ConfigurationManager
.ConnectionStrings["UMSdbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand(
"SELECT ISNULL(MAX(campus_id),0)+1 FROM Campus", con);
cmd.CommandType = CommandType.Text;
tbCampusID.Text = cmd.ExecuteScalar().ToString();
using (SqlCommand cmd1 = new SqlCommand(
"INSERT INTO Campus (campus_id,campus_name)VALUES(@camp_id,camp_name)", con))
{
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.AddWithValue("@campus_id", tbCampusID.Text);
cmd1.Parameters.AddWithValue("@campus_name", tbCampusName.Text);
cmd1.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Saved");
}
}
}
catch (Exception)
{
}
}
答案 0 :(得分:1)
SQL查询和Parameters.AddWithValue
调用中的参数名称必须匹配:
using (SqlCommand cmd1 = new SqlCommand(
"INSERT INTO Campus (campus_id, campus_name) VALUES(@campus_id, @campus_name)", con))
{
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.AddWithValue("@campus_id", tbCampusID.Text);
cmd1.Parameters.AddWithValue("@campus_name", tbCampusName.Text);
cmd1.ExecuteNonQuery();
con.Close();
}
答案 1 :(得分:0)
您正在为尚未定义的占位符添加值。看到这个说法
cmd1.Parameters.AddWithValue("@campus_id", tbCampusID.Text);
在这里,您使用campus_id
作为占位符,并查看插入查询,即INSERT INTO Campus (campus_id,campus_name)VALUES(@camp_id,camp_name)
。占位符为camp_id
并导致错误;像这样使用:
string querySql = "INSERT INTO Campus (campus_id, campus_name) VALUES(@camp_id, @campus_name)"
using (SqlCommand cmd1 = new SqlCommand(querySql, con))
{
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.AddWithValue("@camp_id", tbCampusID.Text);
cmd1.Parameters.AddWithValue("@campus_name", tbCampusName.Text);
cmd1.ExecuteNonQuery();
con.Close();
}