ExecuteNonQuery:尚未初始化连接属性。

时间:2022-07-17 16:29:51

Afternoon, So I have been at this one issue for hours and can't really get past this last hump. Below is the code for this program that I am writing:

下午,所以我花了好几个小时在这个问题上,真的无法度过最后的难关。下面是我正在编写的这个程序的代码:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Diagnostics;  
using System.Data;  
using System.Data.SqlClient;  
using System.Configuration;  

namespace Test  
{  
  class Program  
  {  
    static void Main()  
    {  
      EventLog alog = new EventLog();  
      alog.Log = "Application";  
      alog.MachineName = ".";  
      foreach (EventLogEntry entry in alog.Entries)  
      {  
       SqlConnection connection1 = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=syslog2;Integrated Security=True");  
       SqlDataAdapter cmd = new SqlDataAdapter();  
       cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ");  
       cmd.InsertCommand.Parameters.Add("@EventLog",SqlDbType.VarChar).Value = alog.Log;  
       cmd.InsertCommand.Parameters.Add("@TimeGenerated", SqlDbType.DateTime).Value = entry.TimeGenerated;  
       cmd.InsertCommand.Parameters.Add("@EventType", SqlDbType.VarChar).Value = entry.EntryType;  
       cmd.InsertCommand.Parameters.Add("@SourceName", SqlDbType.VarChar).Value = entry.Source;  
       cmd.InsertCommand.Parameters.Add("@ComputerName", SqlDbType.VarChar).Value = entry.MachineName;  
       cmd.InsertCommand.Parameters.Add("@InstanceId", SqlDbType.VarChar).Value = entry.InstanceId;  
       cmd.InsertCommand.Parameters.Add("@Message", SqlDbType.VarChar).Value = entry.Message;  
       connection1.Open();  
       cmd.InsertCommand.ExecuteNonQuery();  
       connection1.Close();  
      }   
    }  
  }  
} 

The Code compiles fine without error or warning but when i go to run it, as soon as it gets to cmd.InsertCommand.ExecuteNonQuery(); I get the following error:

代码编译良好,没有错误或警告,但是当我运行它时,只要它到达cmd.InsertCommand.ExecuteNonQuery();我得到以下错误:

ExecuteNonQuery: Connection property has not been initialized.

ExecuteNonQuery:尚未初始化连接属性。

Any ideas on what I missed?

有什么想法吗?

7 个解决方案

#1


30  

You need to assign the connection to the SqlCommand, you can use the constructor or the property:

您需要将连接分配给SqlCommand,您可以使用构造函数或属性:

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:

我强烈建议对任何实现IDisposable(比如SqlConnection)的类型使用use -statement,它也会关闭连接:

using(var connection1 = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=syslog2;Integrated Security=True"))
{
    SqlDataAdapter 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.

除此之外,您不需要为foreach中的每个条目创建新的连接和数据适配器,即使创建、打开和关闭连接并不意味着ADO。NET将创建、打开和关闭物理连接,但只查看连接池中可用的连接。然而,这是不必要的开销。

#2


8  

You are not initializing connection.That's why this kind of error is coming to you.

您没有初始化连接。这就是为什么你会犯这种错误。

Your code:

你的代码:

cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ");

Corrected code:

纠正代码:

cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ",connection1);

#3


1  

A couple of things wrong here.

这里有几个问题。

  1. Do you really want to open and close the connection for every single log entry?

    您真的想要为每个日志条目打开并关闭连接吗?

  2. Shouldn't you be using SqlCommand instead of SqlDataAdapter?

    难道您不应该使用SqlCommand而不是SqlDataAdapter吗?

  3. The data adapter (or SqlCommand) needs exactly what the error message tells you it's missing: an active connection. Just because you created a connection object does not magically tell C# that it is the one you want to use (especially if you haven't opened the connection).

    数据适配器(或SqlCommand)需要的正是错误消息告诉您它丢失的内容:活动连接。仅仅因为您创建了一个连接对象,并不会神奇地告诉c#它就是您想要使用的对象(特别是如果您还没有打开连接)。

I highly recommend a C# / SQL Server tutorial.

我强烈推荐c# / SQL Server教程。

#4


1  

Actually this error occurs when server makes connection but can't build due to failure in identifying connection function identifier. This problem can be solved by typing connection function in code. For this I take a simple example. In this case function is con your may be different.

实际上,这个错误发生在服务器建立连接时,但是由于无法识别连接函数标识符而无法构建。这个问题可以通过在代码中输入连接函数来解决。为此,我举一个简单的例子。在这种情况下,功能是可能不同的。

SqlCommand cmd = new SqlCommand("insert into ptb(pword,rpword) values(@a,@b)",con);

#5


0  

Opening and closing the connection takes a lot of time. And use the "using" as another member suggested. I changed your code slightly, but put the SQL creation and opening and closing OUTSIDE your loop. Which should speed up the execution a bit.

打开和关闭连接需要很多时间。并按照其他成员的建议使用“use”。我稍微修改了您的代码,但是将SQL创建、打开和关闭放在循环之外。这会加快执行速度。

  static void Main()
        {
            EventLog alog = new EventLog();
            alog.Log = "Application";
            alog.MachineName = ".";
            /*  ALSO: USE the USING Statement as another member suggested
            using (SqlConnection connection1 = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=syslog2;Integrated Security=True")
            {

                using (SqlCommand comm = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ", connection1))
                {
                    // add the code in here
                    // AND REMEMBER: connection1.Open();

                }
            }*/
            SqlConnection connection1 = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=syslog2;Integrated Security=True");
            SqlDataAdapter cmd = new SqlDataAdapter();
            // Do it one line
            cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ", connection1);
            // OR YOU CAN DO IN SEPARATE LINE :
            // cmd.InsertCommand.Connection = connection1;
            connection1.Open();

            // CREATE YOUR SQLCONNECTION ETC OUTSIDE YOUR FOREACH LOOP
            foreach (EventLogEntry entry in alog.Entries)
            {
                cmd.InsertCommand.Parameters.Add("@EventLog", SqlDbType.VarChar).Value = alog.Log;
                cmd.InsertCommand.Parameters.Add("@TimeGenerated", SqlDbType.DateTime).Value = entry.TimeGenerated;
                cmd.InsertCommand.Parameters.Add("@EventType", SqlDbType.VarChar).Value = entry.EntryType;
                cmd.InsertCommand.Parameters.Add("@SourceName", SqlDbType.VarChar).Value = entry.Source;
                cmd.InsertCommand.Parameters.Add("@ComputerName", SqlDbType.VarChar).Value = entry.MachineName;
                cmd.InsertCommand.Parameters.Add("@InstanceId", SqlDbType.VarChar).Value = entry.InstanceId;
                cmd.InsertCommand.Parameters.Add("@Message", SqlDbType.VarChar).Value = entry.Message;
                int rowsAffected = cmd.InsertCommand.ExecuteNonQuery();
            }
            connection1.Close(); // AND CLOSE IT ONCE, AFTER THE LOOP
        }

#6


-1  

just try this..

试试这个. .

you need to open the connection using connection.open() on the SqlCommand.Connection object before executing ExecuteNonQuery()

您需要在SqlCommand上使用connector .open()打开连接。执行ExecuteNonQuery()之前的连接对象

#7


-1  

double click on your form to create form_load event.Then inside that event write command.connection = "your connection name";

双击窗体创建form_load事件。然后在事件中写入命令。连接=“您的连接名”;

#1


30  

You need to assign the connection to the SqlCommand, you can use the constructor or the property:

您需要将连接分配给SqlCommand,您可以使用构造函数或属性:

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:

我强烈建议对任何实现IDisposable(比如SqlConnection)的类型使用use -statement,它也会关闭连接:

using(var connection1 = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=syslog2;Integrated Security=True"))
{
    SqlDataAdapter 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.

除此之外,您不需要为foreach中的每个条目创建新的连接和数据适配器,即使创建、打开和关闭连接并不意味着ADO。NET将创建、打开和关闭物理连接,但只查看连接池中可用的连接。然而,这是不必要的开销。

#2


8  

You are not initializing connection.That's why this kind of error is coming to you.

您没有初始化连接。这就是为什么你会犯这种错误。

Your code:

你的代码:

cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ");

Corrected code:

纠正代码:

cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ",connection1);

#3


1  

A couple of things wrong here.

这里有几个问题。

  1. Do you really want to open and close the connection for every single log entry?

    您真的想要为每个日志条目打开并关闭连接吗?

  2. Shouldn't you be using SqlCommand instead of SqlDataAdapter?

    难道您不应该使用SqlCommand而不是SqlDataAdapter吗?

  3. The data adapter (or SqlCommand) needs exactly what the error message tells you it's missing: an active connection. Just because you created a connection object does not magically tell C# that it is the one you want to use (especially if you haven't opened the connection).

    数据适配器(或SqlCommand)需要的正是错误消息告诉您它丢失的内容:活动连接。仅仅因为您创建了一个连接对象,并不会神奇地告诉c#它就是您想要使用的对象(特别是如果您还没有打开连接)。

I highly recommend a C# / SQL Server tutorial.

我强烈推荐c# / SQL Server教程。

#4


1  

Actually this error occurs when server makes connection but can't build due to failure in identifying connection function identifier. This problem can be solved by typing connection function in code. For this I take a simple example. In this case function is con your may be different.

实际上,这个错误发生在服务器建立连接时,但是由于无法识别连接函数标识符而无法构建。这个问题可以通过在代码中输入连接函数来解决。为此,我举一个简单的例子。在这种情况下,功能是可能不同的。

SqlCommand cmd = new SqlCommand("insert into ptb(pword,rpword) values(@a,@b)",con);

#5


0  

Opening and closing the connection takes a lot of time. And use the "using" as another member suggested. I changed your code slightly, but put the SQL creation and opening and closing OUTSIDE your loop. Which should speed up the execution a bit.

打开和关闭连接需要很多时间。并按照其他成员的建议使用“use”。我稍微修改了您的代码,但是将SQL创建、打开和关闭放在循环之外。这会加快执行速度。

  static void Main()
        {
            EventLog alog = new EventLog();
            alog.Log = "Application";
            alog.MachineName = ".";
            /*  ALSO: USE the USING Statement as another member suggested
            using (SqlConnection connection1 = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=syslog2;Integrated Security=True")
            {

                using (SqlCommand comm = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ", connection1))
                {
                    // add the code in here
                    // AND REMEMBER: connection1.Open();

                }
            }*/
            SqlConnection connection1 = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=syslog2;Integrated Security=True");
            SqlDataAdapter cmd = new SqlDataAdapter();
            // Do it one line
            cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ", connection1);
            // OR YOU CAN DO IN SEPARATE LINE :
            // cmd.InsertCommand.Connection = connection1;
            connection1.Open();

            // CREATE YOUR SQLCONNECTION ETC OUTSIDE YOUR FOREACH LOOP
            foreach (EventLogEntry entry in alog.Entries)
            {
                cmd.InsertCommand.Parameters.Add("@EventLog", SqlDbType.VarChar).Value = alog.Log;
                cmd.InsertCommand.Parameters.Add("@TimeGenerated", SqlDbType.DateTime).Value = entry.TimeGenerated;
                cmd.InsertCommand.Parameters.Add("@EventType", SqlDbType.VarChar).Value = entry.EntryType;
                cmd.InsertCommand.Parameters.Add("@SourceName", SqlDbType.VarChar).Value = entry.Source;
                cmd.InsertCommand.Parameters.Add("@ComputerName", SqlDbType.VarChar).Value = entry.MachineName;
                cmd.InsertCommand.Parameters.Add("@InstanceId", SqlDbType.VarChar).Value = entry.InstanceId;
                cmd.InsertCommand.Parameters.Add("@Message", SqlDbType.VarChar).Value = entry.Message;
                int rowsAffected = cmd.InsertCommand.ExecuteNonQuery();
            }
            connection1.Close(); // AND CLOSE IT ONCE, AFTER THE LOOP
        }

#6


-1  

just try this..

试试这个. .

you need to open the connection using connection.open() on the SqlCommand.Connection object before executing ExecuteNonQuery()

您需要在SqlCommand上使用connector .open()打开连接。执行ExecuteNonQuery()之前的连接对象

#7


-1  

double click on your form to create form_load event.Then inside that event write command.connection = "your connection name";

双击窗体创建form_load事件。然后在事件中写入命令。连接=“您的连接名”;