Must declare the scalar variable @variableName c# Sql


When u need to pass parameters to sql Query. This can be done in two ways..

First one:

SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);

string query = "select * from table where columnName = '" + txtSearch.Text + "'";

SqlCommandcommand = new SqlCommand(query,connection);

Bur this approach is not recommended. this may lead to error sometimes. So, whenever we need to pass parameters to query, use SqlParamater. The same query can be written as..

string query = "select * from table where columnName =@value";

SqlCommand command = new SqlCommand(query,connection);

command.Parameters.AddWithValue("@value",txtSearch.Text);

Using SqlParameters gives a cleaner, less error prone and SQL injection safe (comparative) code.


2 comments:

  1. Why have you left off the quotation marks on this statement?
    string query = "select * from table where columnName =@value;
    You seem to be having some kind of joke, wasting our time.
    Are you not aware that quotation marks are crucial in programming?

    ReplyDelete
    Replies
    1. Hello Peter. Thanks for pointing out the missing quote. But it should be in some good manner. None of the blogger wastes their time to write articles to waste some others time. Even they are human beings and they do some mistakes. The quote from the line you mentioned was missed mistakenly but not intentionally. Bloggers do allow comments for feedback/questions from readers which also includes pointing out some of the mistakes like these. I agree i did miss the quote but am not here to waste your time.

      Delete