18

午後、それで私はこの1つの問題に何時間もいて、この最後のこぶを本当に乗り越えることができません。以下は私が書いているこのプログラムのコードです:

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:接続プロパティが初期化されていません。

私が逃したものについて何かアイデアはありますか?

4

7 に答える 7

43

に接続を割り当てる必要があります。コンストラクターまたはプロパティSqlCommandを使用できます。

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

のようなusing-statement実装のタイプにはを使用することを強くお勧めします。これにより、接続も閉じられます。IDisposableSqlConnection

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

それとは別に、新しい接続を作成する必要はありませんDataAdapter接続を作成、開く、閉じるとは、 ADO.NETが物理接続を作成、開く、閉じることを意味するのでforeachはなく、を調べるだけです。使用可能な接続の接続プール。それにもかかわらず、それは不必要なオーバーヘッドです。

于 2012-04-21T21:24:15.057 に答える
13

接続を初期化していないため、この種のエラーが発生します。

あなたのコード:

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);
于 2014-07-27T11:38:15.583 に答える
1

ここでいくつか間違っています。

  1. すべてのログエントリの接続を本当に開いたり閉じたりしますか?

  2. SqlCommand代わりに使用するべきではありませんSqlDataAdapterか?

  3. データアダプタ(またはSqlCommand)には、エラーメッセージに表示される内容(アクティブな接続)が必要です。接続オブジェクトを作成したからといって、それが使用したいオブジェクトであることをC#に魔法のように伝えることはありません(特に接続を開いていない場合)。

C#/SQLServerチュートリアルを強くお勧めします。

于 2012-04-21T21:25:14.003 に答える
1

実際、このエラーはサーバーが接続を確立したときに発生しますが、接続機能識別子の識別に失敗したために構築できません。この問題は、コードに接続関数を入力することで解決できます。このために、私は簡単な例を取ります。この場合、機能は異なります。

SqlCommand cmd = new SqlCommand("insert into ptb(pword,rpword) values(@a,@b)",con);
于 2015-08-16T13:23:58.133 に答える
0

接続の開閉には時間がかかります。そして、別のメンバーが提案したように「使用」を使用します。コードを少し変更しましたが、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
        }
于 2017-04-19T10:56:43.187 に答える
-1

これを試してみてください。

connection.open()実行する前に、SqlCommand.Connectionオブジェクトでを使用して接続を開く必要がありますExecuteNonQuery()

于 2012-12-10T06:15:44.627 に答える
-1

フォームをダブルクリックしてform_loadイベントを作成します。次に、そのイベント内にwrite command.connection="接続名";を記述します。

于 2017-03-06T11:37:29.933 に答える