C # SQL Query - ExecuteNonQuery: Connection property not initialized

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

"ExecuteNonQuery: connection property was not initialized

The blocks of code are as follows:

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++; 

Compounds for them are defined at the top of the class.

+4
source share
1 answer

You need to assign a SqlConnection object.

  cmd.Connection = connection; 

Where connection is an SqlConnection object with your connection string, etc.

Also for good practice you should wrap it in using :

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

And parameterized queries to prevent SQL Injection attacks.

+3
source

Source: https://habr.com/ru/post/1502059/


All Articles