How to create a SqlCommand object in C#

This example demonstrates the following functionalities:
1. Create a SqlCommand object.
2. Create two SqlParameter objects.
3. Initialize two SqlParameter objects.
4. Initialize the SqlCommand object.
5. Add two Parameter objects into the Parameters collection of the Command object sqlCommand.

string cmdString = "SELECT user_name, pass_word FROM LogIn ";
cmdString += "WHERE (user_name LIKE @Param1 ) AND (pass_word LIKE @Param2)";
SqlParameter paramUserName = new SqlParameter();
SqlParameter paramPassWord = new SqlParameter();
SqlCommand sqlCommand As New SqlCommand();
paramUserName.ParameterName = "@Param1";
paramUserName.Value = txtUserName.Text;
paramPassWord.ParameterName = "@Param2";
paramPassWord.Value = txtPassWord.Text;
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = cmdString;
sqlCommand.Parameters.Add(paramUserName);
sqlCommand.Parameters.Add(paramPassWord);

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.