为什么我不能在我的静态方法中使用using语句?

时间:2015-05-31 20:26:39

标签: c# sql asp.net ado.net

如果我在课堂上这样使用它正常工作,当我从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;
         }
     }
 }

1 个答案:

答案 0 :(得分:0)

SQLConnection将在返回datareader之前关闭/处置它自己,并且datareader需要一个开放的连接。