ExecuteReader 需要一个开放且可用的连接。连接的当前状态为正在连接



我有一个ASP。. NET网页。它利用了4 BackgroundWorkers。每个bw从数据库中检索一些数据。

连接数据库的代码为:

if (dbConnection.State == ConnectionState.Closed)
{
    dbConnection.Open();
}    
DataTable dt = new DataTable(); 
OdbcCommand cmd = new OdbcCommand(sqlQuery, dbConnection);
cmd.CommandTimeout = 0;
IDataReader dataReader = cmd.ExecuteReader();
dt.Load(dataReader);
dataReader.Close();
dataReader.Dispose();

构造函数中,this.dbConnection = new OdbcConnection(networkdetails);

每个bw都使用上面的代码片段来查询数据库并检索值。代码有时工作得很好。其他时候,它会抛出上面给出的异常。

我可能做错了什么,有什么帮助吗?

尝试处理异常,然后关闭连接。

为此,在'Try'块中编写代码,在' catch '块中捕获异常,并在'Finally'块中关闭连接。

try{
      // Your code
}
catch
{
      // Catch exception
}
Finally
{
      // Close the connection
      dbConnection.Close();
}

最新更新