“必须声明标量变量”错误
必须声明标量变量“@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();
有人能帮我吗?
您应该为参数赋值
cmd.Parameters.AddWithValue("@Id", value);
因为您在SqlCommand
声明了您的Id
参数,但您没有添加任何值。
当您在CommandText
属性中分配文本时,您不需要使用()
。
cmd.CommandText = "SELECT Goal from Planning WHERE Id = @Id"; cmd.Parameters.AddWithValue("@Id", YourIdValue); int goal = (int)cmd.ExecuteScalar();
还可以使用using
语句来处置您的SqlConnection
和SqlCommand
。
这是一个完整的例子;
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); } }