我正在尝试从 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.
将SqlConnection
内部放入 using 块也会导致应用程序挂起,除非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 万行,但由于我只获取 Schema 信息,我认为这不是问题。我的问题是:为什么我的应用程序在尝试关闭连接时卡住了?
解决方案:也许这不是最佳的,但它确实有效;我在调用连接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.