Wor*_*red 6 c# sql sql-server ado.net
我试图从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.
Run Code Online (Sandbox Code Playgroud)
将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);
}
Run Code Online (Sandbox Code Playgroud)
有问题的表有超过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.
Run Code Online (Sandbox Code Playgroud)
很久以前我看到过类似的东西.对我来说,这是因为我做了类似的事情:
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
SqlDataReader reader = command.ExecuteReader();
// here, I started looping, reading one record at a time
// and after reading, say, 100 records, I'd break out of the loop
connection.Close(); // this would hang
Run Code Online (Sandbox Code Playgroud)
问题是该命令似乎想要完成.也就是说,浏览整个结果集.我的结果集有数百万条记录.它最终将完成.
我通过在调用command.Cancel()之前添加一个调用来解决问题connection.Close().
有关详细信息,请参阅http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=610.