We need to pass sqlconnection object to sqlcommand object, before executing it.
Sqlcommand has has following constructors constructor:
- SqlCommand()
- SqlCommand(String)
- SqlCommand(String, SqlConnection)
- SqlCommand(String, SqlConnection, SqlTransaction)
- SqlCommand(String, SqlConnection, SqlTransaction, SqlCommandColumnEncryptionSetting)
If we are using the 1. default constructor or 2. paramterized constructor with one parameter(query), then we need to set connection as
SqlCommand.Connection = SqlConnection;
Below is the working code snippet:
//create a connection object
using (SqlConnection connection = new SqlConnection(connectionString))
{
//create command object, and pass your string query & connection object.
//we can call the default constructor also and later assign these values
SqlCommand command = new SqlCommand(queryString, connection);
//open the connection here,
command.Connection.Open();
//execute the command.
command.ExecuteNonQuery();
}
To ensure that connections are always closed, we should open the connection inside of a using block, to ensure that the connection is automatically closed when the code exits the block.