一个用C#编写的相当大的Web应用程序持续抛出两个错误:
'ExecuteReader需要一个开放和可用的连接。连接的当前状态为打开。'
和
'尝试调用已关闭读取器时的无效操作。'
这些错误是零星发生的——页面通常会正常加载95%的时间,但最近它们变得流行起来,一直发生,并且基本上瘫痪了应用程序的功能。
这个Web应用程序高度依赖于MS SQL数据库,这些错误似乎不仅限于一个页面,而是几乎所有连接到数据库的页面。
查询的执行方式如下:
这些错误是零星发生的——页面通常会正常加载95%的时间,但最近它们变得流行起来,一直发生,并且基本上瘫痪了应用程序的功能。
这个Web应用程序高度依赖于MS SQL数据库,这些错误似乎不仅限于一个页面,而是几乎所有连接到数据库的页面。
查询的执行方式如下:
Database.Open(); // Custom class that has our connection string hard coded.
string query = "SELECT * FROM table"; // (dummy query)
SqlCommand command = new SqlCommand(query, Database.Conn);
SqlDataReader reader = null;
try {
reader = command.ExecuteReader(CommandBehaviour.CloseConnection);
if (reader.HasRows) {
while (reader.Read()) {
// Do something with the data.
}
}
reader.Close();
}
catch (Exception e) {
throw new Exception(e.Message);
}
finally {
if (reader != null) {
reader.Close();
}
}
我在网上查找了这些错误,并尝试了一些潜在的解决方案,但都无济于事:
把代码中的各个部分放到using()代码块中。
为reader指定CommandBehaviour.CloseConnection。
检查是否启用了MARS。
确保每次创建一个新的连接对象。
我花费了很长时间搜索解决方案,更不用说尝试使其正常工作,现在我几乎快要抓狂了!
请帮帮我!
编辑--问题已经解决,请参见评论部分。
private static string connString = "(已删除连接字符串)"; public static SqlConnection Conn = new SqlConnection(connString); public static void Open() { if (Conn.State == System.Data.ConnectionState.Closed) { Conn.Open(); return; } } }`
- shauneba