1

我在一个方法上有这个代码:

DataGrid2.DataSource = Show1(Convert.ToInt32(Request.QueryString["Cr"]));
DataGrid2.DataBind();

这是分配给数据源的 show 方法:

static SqlConnection sqlConntest = new SqlConnection( ConfigurationSettings .AppSettings["conn"].ToString () );

public static SqlDataReader Show1(int cr)
 {
   SqlDataReader dr;
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = sqlConntest;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "sp1";
                cmd.Parameters.Add("@Cr", SqlDbType.Int);
                cmd.Parameters["@Cr"].Value = crewID;
 sqlConntest.Open();
                dr = cmd.ExecuteReader();

                return dr;
}

当我运行程序时,我收到错误消息:

“ExecuteReader 需要一个打开且可用的连接。连接的当前状态为关闭”

为什么会发生这种情况,我该如何解决?谢谢。

4

1 回答 1

1

现在我重新打开了这个问题,因为我提出的副本可能会有所帮助并且是相关的,但似乎不是完全重复的。我将在这里发表我们的评论:

在 ASP.NET 中使用静态连接通常不是一个好主意,如果您使用默认启用的连接池,则更是如此。

你:“我已经从 sqlconnection 中删除了静态属性,但我仍然得到错误

还可以使用using-statement始终尽快关闭连接。您还应该将SqlDataReaderandSqlCommandusing.

你:“我添加了使用,但现在我收到错误“阅读器关闭时对 FieldCount 的尝试无效错误”

我认为这是由于现在连接将在此方法中关闭(这很好)。但是您使用 datareader 作为DataSourceGridViewdatareader 是一个需要与数据库建立开放连接的流。它在 的方法之外使用DataGrid2.DataBind()。因此你得到了例外。

我会简单地使用 aSqlDataAdapter来填充 a DataTable,返回它并使用它来DataSource代替。它只是一个不需要打开连接的内存对象:

public static DataTable Show1(int cr)
{
    DataTable table = new DataTable();
    using (var con = new SqlConnection(ConfigurationSettings.AppSettings["conn"].ToString()))
    using (var cmd = new SqlCommand("sp1", con) { CommandType = CommandType.StoredProcedure })
    using (var da = new SqlDataAdapter(cmd))
        da.Fill(table);  // Fill opens the connection automatically
    return table;
}
于 2014-07-23T21:57:42.420 回答