1

这总是返回一个错误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();
        }
4

2 回答 2

2

您没有指定命令类型。应该是这样的:

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();
    }
于 2016-06-23T17:53:04.790 回答
-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();
        }
于 2012-04-23T07:03:04.587 回答