必须声明标量变量“@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();
有人能帮助我吗?
答案 0 :(得分:2)
因为您在Id
中声明了SqlCommand
参数,但未添加任何值。
当你在CommandText
财产中分配文字时,你不需要使用()
。
cmd.CommandText = "SELECT Goal from Planning WHERE Id = @Id";
cmd.Parameters.AddWithValue("@Id", YourIdValue);
int goal = (int)cmd.ExecuteScalar();
还可以使用using
statement来处置您的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);
}
}
答案 1 :(得分:2)
您应该为参数
指定一个值cmd.Parameters.AddWithValue("@Id", value);