Home >Backend Development >C++ >Why Does `ExecuteNonQuery` Throw a 'Connection Property Not Initialized' Error in .NET?

Why Does `ExecuteNonQuery` Throw a 'Connection Property Not Initialized' Error in .NET?

Barbara Streisand
Barbara StreisandOriginal
2025-01-05 15:54:40749browse

Why Does `ExecuteNonQuery` Throw a

ExecuteNonQuery: Connection Property Not Initialized

Problem

A developer encountered an error while running a .NET program due to the "ExecuteNonQuery: Connection property has not been initialized" message.

Code Sample

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();
        }
    }
}

Solution

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;

Using Statement Recommendation

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
}

Optimizing Connection Management

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn