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

下午,所以我在这个问题上待了好几个小时,无法真正克服最后一个困难。以下是我正在编写的该程序的代码:


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

      }   

    }  

  }  

该代码可以正常编译,没有错误或警告,但是当我运行它时,只要它到达cmd.InsertCommand.ExecuteNonQuery();就可以了。我收到以下错误:


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


关于我错过的任何想法?


人到中年有点甜
浏览 985回答 3
3回答

倚天杖

您不是在初始化连接,这就是为什么出现这种错误的原因。您的代码:cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ");更正的代码:cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ",connection1);

慕村225694

您不是在初始化连接,这就是为什么出现这种错误的原因。您的代码:cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ");更正的代码:cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ",connection1);
打开App,查看更多内容
随时随地看视频慕课网APP