为什么我不能在我的静态方法中使用 using 语句?
Why I cannot use the using statement with my static method?
如果我在 class 中这样使用它,当我从 default.cs 中调用它时它工作正常:
public class MyMethodsSql
{
public static SqlDataReader MetodoCommand()
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection(CS);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from Employees";
con.Open();
cmd.Connection = con;
SqlDataReader sdr = cmd.ExecuteReader();
return sdr;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
GridView1.DataSource = MyMethodsSql.MetodoCommand();
GridView1.DataBind();
}
但是当我使用 using 语句时出现错误:表示没有打开的连接
public class MyMethodsSql
{
public static SqlDataReader MetodoCommand()
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from Employees";
con.Open();
cmd.Connection = con;
SqlDataReader sdr = cmd.ExecuteReader();
return sdr;
}
}
}
SQLConnection 将在返回数据读取器之前close/dispose 自身,并且数据读取器需要一个打开的连接。
如果我在 class 中这样使用它,当我从 default.cs 中调用它时它工作正常:
public class MyMethodsSql
{
public static SqlDataReader MetodoCommand()
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection(CS);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from Employees";
con.Open();
cmd.Connection = con;
SqlDataReader sdr = cmd.ExecuteReader();
return sdr;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
GridView1.DataSource = MyMethodsSql.MetodoCommand();
GridView1.DataBind();
}
但是当我使用 using 语句时出现错误:表示没有打开的连接
public class MyMethodsSql
{
public static SqlDataReader MetodoCommand()
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from Employees";
con.Open();
cmd.Connection = con;
SqlDataReader sdr = cmd.ExecuteReader();
return sdr;
}
}
}
SQLConnection 将在返回数据读取器之前close/dispose 自身,并且数据读取器需要一个打开的连接。