Question

I have a number of blocks of code in my Windows Application that use the same structure to execute queries. After adding in a few new things to my code, these no longer work due to the error:

"ExecuteNonQuery: Connection property has not been initialized"

Blocks of code all look like this:

sc.Open();
cmd = new SqlCommand("UPDATE bin SET serialNumber=" + tb_computername.Text + " WHERE binNumber=" + binNumber);
cmd.ExecuteNonQuery();
sc.Close();
break;

The new code does this:

//Find Open BIN
int binNumber = 0;
int binIndex = 0;
string queryString = "SELECT * FROM bin";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, scb);
DataSet binNumbers = new DataSet();
adapter.Fill(binNumbers, "bin");
for (int i = 0; i < 150; i++)
{
    binNumber++;                    
    if(binNumbers.Tables["bin"].Rows[binIndex]["serialNumber"].ToString() == "")
{
sc.Open();
cmd = new SqlCommand("UPDATE bin SET serialNumber=" + tb_computername.Text + " WHERE binNumber=" + binNumber);
cmd.ExecuteNonQuery();
sc.Close();
break;
}
binIndex++;

The connections for these are defined at the top of the class.

Was it helpful?

Solution

You need to assign it a SqlConnection object.

 cmd.Connection = connection;

Where connection is a SqlConnection object with your connection string etc.

Also for good practice you should wrap it in a using:

 using (SqlConnection connection = new SqlConnection("ConnectionString")) { 
     cmd.Connection = connection;
 } 

And paramerterized queries to prevent SQL Injection attacks.

OTHER TIPS

We need to pass sqlconnection object to sqlcommand object, before executing it.

Sqlcommand has has following constructors constructor:

  1. SqlCommand()
  2. SqlCommand(String)
  3. SqlCommand(String, SqlConnection)
  4. SqlCommand(String, SqlConnection, SqlTransaction)
  5. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top