SQL Server の SQL テーブルから C# で列情報を取得しようとしています。このリンクの例に従っています: http://support.microsoft.com/kb/310107接続を閉じようとすると、プログラムがハングアップします。接続が閉じられていない場合、プログラムは例外なしで終了します。これが私のコードです:
SqlConnection connection = new SqlConnection(@"MyConnectionString");
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo); // If this is changed to CommandBehavior.SchemaOnly, the program runs fast.
DataTable table = reader.GetSchemaTable();
Console.WriteLine(table.Rows.Count);
connection.Close(); // Alternatively If this line is commented out, the program runs fast.
をusingブロック内に配置すると、が に変更されSqlConnection
ない限り、アプリケーションがハングする原因にもなります。CommandBehavior.KeyInfo
CommandBehavior.SchemaOnly
using (SqlConnection connection = new SqlConnection(@"MyConnectionString"))
{
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo); // If this is changed to CommandBehavior.SchemaOnly, the program runs fast even here in the using
DataTable table = reader.GetSchemaTable();
Console.WriteLine(table.Rows.Count);
}
問題のテーブルには 300 万行以上ありますが、スキーマ情報を取得しているだけなので、問題にはならないと思います。私の質問は、接続を閉じようとしているときにアプリケーションが動かなくなるのはなぜですか?
解決策:これは最適ではないかもしれませんが、うまくいきます。接続時に呼び出されるcommand.Cancel();
直前にステートメントを挿入しました。Close
SqlConnection connection = new SqlConnection(@"MyConnectionString");
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo); // If this is changed to CommandBehavior.SchemaOnly, the program runs fast.
DataTable table = reader.GetSchemaTable();
Console.WriteLine(table.Rows.Count);
command.Cancel(); // <-- This is it.
connection.Close(); // Alternatively If this line is commented out, the program runs fast.