【问题标题】:Must declare the scalar variable "@GenName" [duplicate]必须声明标量变量“@GenName”[重复]
【发布时间】:2019-01-19 20:45:27
【问题描述】:

尝试运行以下代码时出现此错误。对我做错了什么有任何见解吗?我对此很陌生,并且想让它工作得非常糟糕。到目前为止,在我提出的上一个问题中,我从该网站获得的帮助为零。但是在放弃stackoverflow之前决定再给这个论坛一次机会

protected void SaveButton_Click(object sender, EventArgs e)
{
    SqlConnection myConnection =
    new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=TESTdatabase;Integrated Security=True");
    SqlCommand myCommand = new SqlCommand(
    "INSERT into tblGenerator (GeneratorName, GeneratorAddress, GeneratorCity, GeneratorState, GeneratorZip, GeneratorPhone, GeneratorContact, GeneratorEPAID)" +
    "VALUES (@GenName, @GenAdd, @GenCity, @GenState, @GenZip, @GenPhone, @GenContact, @GenEPAID), myConnection");
    myCommand.Parameters.AddWithValue("@GeneratorName", GenName.Text);
    myCommand.Parameters.AddWithValue("@GeneratorAddress", GenAdd.Text);
    myCommand.Parameters.AddWithValue("@GeneratorCity", GenCity.Text);
    myCommand.Parameters.AddWithValue("@GeneratorState", GenState.Text);
    myCommand.Parameters.AddWithValue("@GeneratorZip", GenZip.Text);
    myCommand.Parameters.AddWithValue("@GeneratorPhone", GenPhone.Text);
    myCommand.Parameters.AddWithValue("@GeneratorContact", GenContact.Text);
    myCommand.Parameters.AddWithValue("@GeneratorEPAID", GenEPAID.Text);            

    myConnection.Open();
    myCommand.Connection = myConnection;
    myCommand.ExecuteNonQuery();
    myConnection.Close();
}

【问题讨论】:

  • [@GenName] 与 [@GeneratorName] 不同
  • 和你之前的问题一样,连接对象不在双引号内。
  • 非常感谢您的回复,我弄错了应该放在引号中的对象,并且使用了 sql 表中的字段名称。
  • @Mr.B LarsTech 谈论的是myConnection,您也将其放入查询字符串中,就像在上一个问题中一样。你用语法高亮了它。你应该打电话给docs.microsoft.com/en-us/dotnet/api/…,你打电话给docs.microsoft.com/en-us/dotnet/api/…
  • 啊啊哈。我现在看到@GSerg。谢谢你,先生。

标签: c# ado.net sqlconnection


【解决方案1】:

首先,Stackoverflow 很有帮助 :) 不要放弃这个平台。

现在回答你的问题:

您的 SQL 语句期望的参数是:

(@GenName, @GenAdd, @GenCity, @GenState, @GenZip, @GenPhone, @GenContact, @GenEPAID)

当您稍后为它们分配不同的名称时。

应该是:

    myCommand.Parameters.AddWithValue("@GenName", GenName.Text);
    myCommand.Parameters.AddWithValue("@GenAdd", GenAdd.Text);
    myCommand.Parameters.AddWithValue("@GenCity", GenCity.Text);
    myCommand.Parameters.AddWithValue("@GenState", GenState.Text);
    myCommand.Parameters.AddWithValue("@GenZip", GenZip.Text);
    myCommand.Parameters.AddWithValue("@GenPhone", GenPhone.Text);
    myCommand.Parameters.AddWithValue("@GenContact", GenContact.Text);
    myCommand.Parameters.AddWithValue("@GenEPAID", GenEPAID.Text);

使用 @parameter 时,必须为具有相同名称的参数赋值。

【讨论】:

  • 谢谢!我将立即尝试。
  • 不客气 :) 如果有帮助,请告诉我
  • 好吧,这消除了标量变量错误。但是现在在 myCommand.ExecuteNonQuery() 上抛出了错误的语法错误
  • 你应该在VALUES ...之前加一个空格,像这样:`VALUES ...`
猜你喜欢
  • 2018-09-04
  • 1970-01-01
  • 1970-01-01
  • 2020-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-03
  • 1970-01-01
相关资源
最近更新 更多