Home >Backend Development >C++ >Why Does `ExecuteNonQuery` Throw a 'Connection Property Not Initialized' Error in .NET?
A developer encountered an error while running a .NET program due to the "ExecuteNonQuery: Connection property has not been initialized" message.
The following code sample illustrates the issue:
using System.Data.SqlClient; namespace Test { class Program { static void Main() { SqlConnection connection = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=syslog2;Integrated Security=True"); SqlCommand cmd = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) "); connection.Open(); // Connection is not assigned to the command cmd.ExecuteNonQuery(); connection.Close(); } } }
To resolve the issue, the connection property of the SqlCommand must be assigned. This can be done during command creation or by setting the property later.
Assigning During Command Creation
SqlCommand cmd = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ", connection);
Setting the Property Later
cmd.Connection = connection;
For objects that implement IDisposable, such as SqlConnection, the using statement is recommended. It automatically closes the connection and handles any exceptions:
using (var connection = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=syslog2;Integrated Security=True")) using (var cmd = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ")) { cmd.Connection = connection; // Connection is automatically closed when leaving the using block }
To optimize performance, it's not necessary to create a new connection and data adapter for each entry in the foreach loop. ADO.NET automatically manages connections and uses connection pooling.
The above is the detailed content of Why Does `ExecuteNonQuery` Throw a 'Connection Property Not Initialized' Error in .NET?. For more information, please follow other related articles on the PHP Chinese website!