Reputation: 38613
This always returns an error at cmd.ExecuteScalar()
telling me that The parameterized query '(@Name nvarchar(4000))select count(*) from Locations where name=' expects the parameter '@Name', which was not supplied.
What have I done wrong? location is a string.
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();
}
Upvotes: 1
Views: 5401
Reputation: 21
You did not specify the command type. Should be something like:
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();
}
Upvotes: 2
Reputation: 71
Use like this it helps you....
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();
}
Upvotes: -1