Reputation: 43
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.
Upvotes: 4
Views: 1980
Reputation: 574
We need to pass sqlconnection object to sqlcommand object, before executing it.
Sqlcommand has has following constructors constructor:
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.
Upvotes: 0
Reputation: 70776
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.
Upvotes: 3