在数据库中更新时出错

时间:2014-07-07 11:13:36

标签: c# sql-server

我在使用C#更新数据库时遇到错误。这是代码:

string connectionstring = "server=AMAN;database=student;Integrated Security=True";
SqlConnection conn;
string Admission_no = txtAddmissionNo.Text;
SqlCommand cmd;
conn = new SqlConnection(connectionstring);
conn.Open();
string query = "update fees set prospectues_fee=@prospectues_fee, registration_fee=@registration_fee,admission_fee=@admission_fee ,security_money=@security_money,misslaneous_fee=@misslaneous_fee,development_fee=@development_fee,transport_fair=@transport_fair,computer_fee=@computer_fee ,activity=@activity,hostel_fee=@hostel_fee,dely_fine=@dely_fine,back_dues=@back_dues,tution_feemonth=@tution_feemonth ,tution_fee=@tution_fee,other_fee=@other_fee,total=@total,deposit=@deposit,dues=@dues where Admission_no=@Admission_no";
cmd=new SqlCommand(query,conn);
cmd.Parameters.AddWithValue("@Admission_no", Admission_no);
cmd.Parameters.AddWithValue("@prospectues_fee", prospectues_fee);
cmd.Parameters.AddWithValue("@registration_fee", registration_fee);
cmd.Parameters.AddWithValue("@admission_fee", admission_fee);
cmd.Parameters.AddWithValue("@security_money", security_money);
cmd.Parameters.AddWithValue("@misslaneous_fee", misslaneous_fee);
cmd.Parameters.AddWithValue("@development_fee", development_fee);
cmd.Parameters.AddWithValue("@transport_fair", transport_fair);
cmd.Parameters.AddWithValue("@computer_fee", computer_fee);
cmd.Parameters.AddWithValue("@activity", activity);
cmd.Parameters.AddWithValue("@hostel_fee", hostel_fee);
cmd.Parameters.AddWithValue("@dely_fine", dely_fine);
cmd.Parameters.AddWithValue("@back_dues", back_dues);
cmd.Parameters.AddWithValue("@tution_fee", tution_fee);
cmd.Parameters.AddWithValue("@other_fee", other_fee);
cmd.Parameters.AddWithValue("@total", total);
cmd.Parameters.AddWithValue("@tution_feemonth", tution_feemonth);
cmd.Parameters.AddWithValue("@deposit", deposit_fee);
cmd.Parameters.AddWithValue("@dues", dues);

cmd  = new SqlCommand(query, conn);

try
{
    cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}

错误是@prospectues_fee标量必须声明,我已经声明了。

1 个答案:

答案 0 :(得分:4)

错误比我想象的更简单:

cmd  = new SqlCommand(query, conn);
... // lots of code
cmd  = new SqlCommand(query, conn);
try
{
    cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}

您正在执行之前创建第二个命令;第二个命令有文本但没有参数。删除第二个new SqlCommand行。


这听起来像是可怕的null vs DBNull问题。参数中的null表示"不发送此消息"。哪个真的很傻,但我们就是。试试:

cmd.Parameters.AddWithValue("@prospectues_fee",
    ((object)prospectues_fee) ?? DBNull.Value);

现在重复所有参数......或者只是添加一个循环遍历它们并检查它们的方法:

static void FixTheCrazy(DbCommand command) {
    foreach(DbParameter param in command.Parameters) {
        if(param.Value == null) param.Value = DBNull.Value;
    }
}

或者,使用像dapper这样的工具来为您完成:

using(varconn = new SqlConnection(connectionstring))
{
    conn.Execute(query, new {
        Admission_no, prospectues_fee, registration_fee, ...
        deposit_fee, dues });
}