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.
Advertisement
Answer
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.