问题描述
当我单击以从数据库中获取数据时,我正在使用Web应用程序,但出现以下错误:
I am wiorking on a web application when i click on to fetch data from database i get the following error:
ExecuteReader需要一个开放且可用的连接。连接的当前状态为关闭。
ExecuteReader requires an open and available Connection. The connection's current state is closed.
我在一个单独的类上声明我的连接,如下所示:
I declare my connection on a seperate class as the following:
public Database()
{
valid = false;
using (connection = new SqlConnection(connectionString))
{
connection.Open();
}
}
我在哪里得到错误:
,我从WebForm调用它。当连接已经打开时,为什么会出现此错误(我曾经使用过odbc连接,但工作正常,但是SqlConnection无法正常工作)
and i call it from a WebForm. Why do i get this error when the connection is already open (I used to use odbc connection and it works fine, however the SqlConnection is not working)
原因是什么? ?
推荐答案
仅在使用范围内打开SQL连接:
SQL connection is open within using scope only:
using (var connection = new SqlConnection(connectionString)) {
connection.Open(); // open here
...
} // close here
将您的命令放入使用
范围:
using (var connection = new SqlConnection(connectionString)) {
connection.Open();
// command creation and execution should be within connection "using" scope
using (var q = new SqlCommand()) {
q.Connection = connection;
...
// reader should be within command "using" scope
using (var reader = q.ExecuteReader()) {
...
}
}
...
} // close here
这篇关于“ ExecuteReader需要打开且可用的连接。连接的当前状态为关闭。在WebForm上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!