为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
人到中年有点甜 2019-11-03 08:04:17
下午,所以我在这个问题上待了好几个小时,无法真正克服最后一个困难。以下是我正在编写的该程序的代码: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:连接属性尚未初始化。关于我错过的任何想法?
查看完整描述

3 回答

?
倚天杖

TA贡献1828条经验 获得超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);



查看完整回答
反对 回复 2019-11-04
?
慕村225694

TA贡献1880条经验 获得超4个赞

您不是在初始化连接,这就是为什么出现这种错误的原因。


您的代码:


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



查看完整回答
反对 回复 2019-11-04
  • 3 回答
  • 0 关注
  • 984 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信