【问题标题】:Must declare the scalar variable @firstname [closed]必须声明标量变量@firstname [关闭]
【发布时间】:2019-07-02 07:31:39
【问题描述】:

我正在使用参数化查询,但出现错误 - 我该如何解决?

这是我的代码

SqlCommand cmd = new SqlCommand();
string sql = @"insert into Student_Records (FirstName,LastName,Email,ContactNumber,DOB,TemporaryAddress,PermanentAddress,FatherName,Fathersoccupation,ContactNumberF,MotherName,Mothersoccupation,ContactNumberM,Remarks) values(@firstname,@lastname,@email,@contactnumber,@dob,@temporaryaddress,@permanentaddress,@fathername,@fatheroccupation,@contactnumberf,@mothername,@motheroccupation,@contactnumberm,@remarks) ";
cmd.Parameters.AddWithValue("@firstname", txtFname.Text);
cmd.Parameters.AddWithValue("@lastname", txtlastN.Text);
cmd.Parameters.AddWithValue("@contactnumber", txtCN.Text);
cmd.Parameters.AddWithValue("@dob", dtdob.Value);
cmd.Parameters.AddWithValue("@temporaryaddress", txtTaddress.Text);
cmd.Parameters.AddWithValue("@permanentaddress", txtPaddress.Text);
cmd.Parameters.AddWithValue("@fathername", txtFname.Text);
cmd.Parameters.AddWithValue("@fatheroccupation", txtFoccupation.Text);
cmd.Parameters.AddWithValue("@contactnumberf", txtFcn.Text);
cmd.Parameters.AddWithValue("@mothername", txtMname.Text);
cmd.Parameters.AddWithValue("@motheroccoupation", txtMoccupation.Text);
cmd.Parameters.AddWithValue("@contactnumberm", txtMcn);
cmd.Parameters.AddWithValue("@remarks", rtremarks.Text);
DBconnection.ExecutiveNonQuery(sql);

我收到此错误:

必须声明标量变量

【问题讨论】:

  • 你没有使用SqlCommand。当然,您正在创建它并填充参数,但您并没有使用它来运行您的命令。
  • 这不是你实际使用的代码,因为ExecutiveNonQuery 不会编译?我怀疑问题在于您没有为 @email 而不是 @firstname 添加参数。如果您可以复制并粘贴有问题的代码和错误逐字,我们可能会提供更好的帮助。

标签: c# .net sql-server


【解决方案1】:
using (SqlCommand cmd = new SqlCommand("Add your insert cmd", connection)) {
   cmd.Parameters.AddWithValue("@firstname", txtFname.Text);
   ....
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    相关资源
    最近更新 更多