这始终会在cmd.ExecuteScalar()
返回错误,告诉我The parameterized query '(@Name nvarchar(4000))select count(*) from Locations where name=' expects the parameter '@Name', which was not supplied.
我做错了什么? 位置是一个字符串。
int count = 0;
using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("select count(*) from Locations where name=@Name", conn);
cmd.Parameters.AddWithValue("@Name",location);
conn.Open();
count = (int)cmd.ExecuteScalar();
conn.Close();
}
答案 0 :(得分:1)
您没有指定命令类型。应该是这样的:
using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("select count(*) from Locations where name=@Name", conn);
cmd.Parameters.AddWithValue("@Name",location);
cmd.CommandType = System.Data.CommandType.Text;
conn.Open();
count = (int)cmd.ExecuteScalar();
conn.Close();
}
答案 1 :(得分:-1)
使用这样可以帮助你......
int count = 0;
using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("select count(*) from Locations where name=@Name", conn);
SqlParameter paramName = new SqlParameter("@Name", SqlDbType.VarChar, 255) { Value = "Avinash" };
command.Parameters.Add(paramName);
conn.Open();
count = (int)cmd.ExecuteScalar();
conn.Close();
}