【问题标题】:"Must declare scalar variable" error [duplicate]“必须声明标量变量”错误[重复]
【发布时间】:2014-02-08 13:56:22
【问题描述】:

必须声明标量变量“@Id”

SqlConnection con = new SqlConnection(@"connectionstring");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = ("SELECT Goal from Planning WHERE Id = @Id");
int goal = (int)cmd.ExecuteScalar();

有人可以帮助我吗?

【问题讨论】:

  • 第一行是你的错误信息吗?
  • 是的,这是我的第一条错误消息
  • 顺便说一句,您的 连接字符串 似乎也错了。如果你的connectionstring 是一个变量,你应该像new SqlConnection(connectionstring) 一样使用它而不是new SqlConnection(@"connectionstring")

标签: c# sql-server


【解决方案1】:

你应该给你的参数一个值

cmd.Parameters.AddWithValue("@Id", value);
【解决方案2】:

因为您在 SqlCommand 中声明了您的 Id 参数,但您没有添加任何值。

当您在 CommandText 属性中分配文本时,您不需要使用 ()

cmd.CommandText = "SELECT Goal from Planning WHERE Id = @Id";
cmd.Parameters.AddWithValue("@Id", YourIdValue);
int goal = (int)cmd.ExecuteScalar();

还可以使用using statement 来处理您的SqlConnectionSqlCommand

这里是一个完整的例子;

using(SqlConnection con = new SqlConnection(connString))
using(SqlCommand cmd = new SqlCommand())
{
     cmd.Connection = con;
     cmd.CommandText = "SELECT Goal from Planning WHERE Id = @Id";
     cmd.Parameters.AddWithValue("@Id", YourIdValue);
     try
     {
         conn.Open();
         int goal = (int)cmd.ExecuteScalar();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 2014-08-06
    • 2017-09-24
    相关资源
    最近更新 更多