How to Execute Parameterized SQL Statements: ADO.NET

As we know, SQL statements can be of simple type or may be parameterized. The parameterized query contains some parameters, which may be accepted through object of SqlParameter class. SqlParameter class is used to create the parameters used by the command object to execute the Sql queries.
Write the following code to select a record from the table groups which has a given name. The name is passed by the parameter i.e. Sql Parameter.
SqlConnection connection = new SqlConnection();
connection.ConnectionString = "Data Source= (LocalDb)\\v11.0; Initial Catalog=StockDb; Integrated Security=True";
SqlCommand command = new SqlCommand("select * from Groups where code=@code", connection);
command.Parameters.AddWithValue("@code", 04);
SqlDataReader dr = command.ExecuteReader();

Look out the command object which have a variable name @code. It is the syntax of parameter used. In the next line, the parameter is added by using the function AddWithValue(). This method takes two parameter i.e. one for variable name (same as used in command object) and the second one is its value.

Now when we execute this code, a single record having code = 04 will be returned and can be accessed by data reader object dr.

We can check the rows as the same procedure as in previous post.
How to Execute Parameterized SQL Statements: ADO.NET How to Execute Parameterized SQL Statements: ADO.NET Reviewed by Subhash Sharma on September 19, 2013 Rating: 5

No comments