ExecuteNonQuery: Connection property has not been initialized.
You need to assign the connection to the SqlCommand
, you can use the constructor or the property:
cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ");
cmd.InsertCommand.Connection = connection1;
I strongly recommend to use the using-statement
for any type implementing IDisposable
like SqlConnection
, it'll also close the connection:
using(var connection1 = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=syslog2;Integrated Security=True"))
using(var cmd = new SqlDataAdapter())
using(var insertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) "))
{
insertCommand.Connection = connection1;
cmd.InsertCommand = insertCommand;
//.....
connection1.Open();
// .... you don't need to close the connection explicitely
}
Apart from that you don't need to create a new connection and DataAdapter
for every entry in the foreach
, even if creating, opening and closing a connection does not mean that ADO.NET will create, open and close a physical connection but just looks into the connection-pool for an available connection. Nevertheless it's an unnecessary overhead.
ExecuteNonQuery: Connection property has not been initialized.'
This is the code that I ended up using. Thanks everyone for your help.
SqlConnection myConnection =
new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=TESTdatabase;Integrated Security=True");
SqlCommand myCommand = new SqlCommand(
"INSERT into tblGenerator (GeneratorName, GeneratorAddress, GeneratorCity, GeneratorState, GeneratorZip, GeneratorPhone, GeneratorContact, GeneratorEPAID)" +
"VALUES (@GenName, @GenAdd, @GenCity, @GenState, @GenZip, @GenPhone, @GenContact, @GenEPAID)");
myCommand.Parameters.AddWithValue("@GenName", GenName.Text);
myCommand.Parameters.AddWithValue("@GenAdd", GenAdd.Text);
myCommand.Parameters.AddWithValue("@GenCity", GenCity.Text);
myCommand.Parameters.AddWithValue("@GenState", GenState.Text);
myCommand.Parameters.AddWithValue("@GenZip", GenZip.Text);
myCommand.Parameters.AddWithValue("@GenPhone", GenPhone.Text);
myCommand.Parameters.AddWithValue("@GenContact", GenContact.Text);
myCommand.Parameters.AddWithValue("@GenEPAID", GenEPAID.Text);
myConnection.Open();
myCommand.Connection = myConnection;
MessageBox.Show("You Have Successfully Added a New Generator To SQL");
myCommand.ExecuteNonQuery();
myConnection.Close();
ExecuteNonQuery. connection property has not been initialized
Error message is clear;
connection property has not been initialized
Connect your SqlComamnd
and SqlConnection
like;
SqlCommand cmd = new SqlCommand(sql, conn);
Weird part is, you add your insert values with string concatenation but also you try to add them as parameters also. Read: Give me parameterized SQL, or give me death. And you don't need DBOpen
and DBClose
methods like this.
As a best practice, use using
statement to dispose your SqlComamnd
and SqlConnection
instead of calling .Close()
method manually in a different method, and stop using AddWithValue
method. It may generate unexpected results. Use .Add()
method or it's overloads instead.
Read: Can we stop using AddWithValue()
already?
using(SqlConnection conn = new SqlConnection(source))
using(SqlCommand cmd = conn.CreateCommand())
{
// Set your CommandText property with parameterized way.
// Add your parameters with .Add() method
// Open your connection
// Execute your query.
}
When you get any error message or exception in your code, read them carefully. One more time, and one more time.. This makes much more easier to solve your problem.
SQL and C#: ExecuteNonQuery: Connection property has not been initialized
Use:
string CS = ConfigurationManager.ConnectionString["<ConnectionString located in web.config file or Create it in web.config file>"].connectionString;
using(SqlConnection con = new SqlConnection(CS))
{
con.Open();
query = "INSERT INTO Product(ProductCode, ProductName, ProductType, Brand, Quantity, Measurements, Price)
VALUES(@ProductCode,@ProductName,@ProductType,@Brand,@Quantity,@Meter,@Price)";
using(SqlCommand cmd = new SqlCommand(query,con))
{
cmd.Parameters.AddWithValue("@ProductCode", txtprocode.Text);
cmd.Parameters.AddWithValue("@ProductName", txtproname.Text);
cmd.Parameters.AddWithValue("@ProductType", txtprotype.Text);
cmd.Parameters.AddWithValue("@Brand", txtbrand.Text);
cmd.Parameters.AddWithValue("@Quantity", txtquantity.Text);
cmd.Parameters.AddWithValue("@Meter", txtmeasurements.Text);
cmd.Parameters.AddWithValue("@Price", txtprice.Text);
cmd.ExecuteNonQuery();
con.Close();
}
}
By the way you error was in @Meter and @Measurements
In SQL query you write it @Meter and in
cmd.Parameters.AddWithValue("@Measurements");
System.InvalidOperationException: 'ExecuteNonQuery: Connection property has not been initialized.'
You are not using your SqlConnection. You need to pass it into the constructor of SqlCommand like this:
cmd = new SqlCommand("UPDATE Report set Quantity=x.q from (SELECT Variety, SUM(Quantity) as q FROM Inventory GROUP BY Variety) x where Report.Variety=x.Variety", con);
Error ExecuteNonQuery: Connection property has not been initialized C# (Access)
You use disposed (closed with all resources released) connection:
private OleDbConnection openConnection()
{
// you create the connection
using var conn= new OleDbConnection(connString);
conn.Open();
return conn;
} // <- and here you dispose it
The very same problem with Command
: the cmd
you return is disposed.
private OleDbCommand getCommand(string queryString, OleDbConnection conn)
{
using var cmd = new OleDbCommand(queryString, conn); // <- command created
return cmd;
} // <- and disposed
You can drop using
in both methods:
private OleDbConnection openConnection()
{
// we create connection
conn = new OleDbConnection(connString);
try {
// try it to open
conn.Open();
// return opened (and not disposed!) connection
return conn;
}
catch {
// on open failure we dispose conenction (to prevent resources leakage)
conn.Dispose();
// and rethrow the exception (to know the exact problem)
throw;
}
}
// Here we just return a command
private OleDbCommand getCommand(string queryString, OleDbConnection conn) =>
new OleDbCommand(queryString, conn);
Or may be merge methods into one:
public int Command(string queryCommand)
{
using var conn = new OleDbConnection(connString);
conn.Open();
using var cmd = new OleDbCommand(queryString, conn);
return cmd.ExecuteNonQuery();
} // here both conn and cmd will be disposed
ExecuteNonQuery: Connection property has not been initialized. Sqlparameter array
You didn't tell your SqlCommand
that it should work with your SqlConnetion
.
Also, SqlCommand
implements the IDisposable
interface so you should be using it inside the using
statement:
private string executescaler(string con, CommandType commandTyp, string procedure, SqlParameter[] sqlParameter)
{
string res;
using (var connection = new SqlConnection(con))
{
using(var cmd = new SqlCommand(procedure, con))
{
cmd.CommandType = commandTyp;
cmd.Parameters.AddRange(sqlParameter);
connection.Open();
res = cmd.ExecuteNonQuery().ToString();
}
}
return res;
}
C# SQL Query - ExecuteNonQuery: Connection property has not been initialized
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.
Related Topics
Differencebetween Await Task<T> and Task<T>.Result
How to Count Duplicates in List with Linq
When Is a Static Constructor Called in C#
Shorter Syntax for Casting from a List<X> to a List<Y>
Regular Expression to Remove HTML Tags
Why Should I Prefer Single 'Await Task.Whenall' Over Multiple Awaits
Gradient Circles for Map Generator
Multiple Httppost Method in Web API Controller
Adding Multiple Parameterized Variables to a Database in C#
Add Data Annotations to a Class Generated by Entity Framework
Get Mime Type from Filename Extension
How to Get the Calling Method Name and Type Using Reflection
Most Efficient Way to Remove Special Characters from String
Get Last 10 Lines of Very Large Text File > 10Gb
Is There a .Net/C# Wrapper for SQLite
Trying to Run Multiple Http Requests in Parallel, But Being Limited by Windows (Registry)
How to Update UI from Another Thread Running in Another Class