【问题标题】:Why I cannot use the using statement with my static method? [duplicate]为什么我的静态方法不能使用 using 语句? [复制]
【发布时间】:2015-08-14 06:02:33
【问题描述】:

如果我在一个类中这样使用它可以正常工作,当我从 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;
         }
     }
 }

【问题讨论】:

  • 当您退出右大括号时,using 语句会关闭连接。当连接关闭时,SqlDataReader 也会关闭。

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


【解决方案1】:

SQLConnection 将在返回数据读取器之前关闭/处理自己,数据读取器需要打开连接。

【讨论】:

  • 好的,这意味着我应该在最后使用 con.Close(); 而不是 using 语句在 try catch 和 finally 中,但从不使用 using?
  • @AlexMartinez:关闭连接与处理连接具有相同的效果。如果要返回数据读取器,则无法在方法中关闭连接。为了保持责任合理,您应该将连接发送到方法并返回阅读器,或者在方法中进行读取,以便您可以关闭连接并返回数据。
  • 您仍然可以使用 using 语句,将 con 设为类的私有变量并在 MyMethodsSql 上实现 IDisposable,在构造函数中打开 sql 连接并在 Dispose() 中关闭连接,这样调用者可以使用 SqlConnection 和 MyMethodsSql
  • 感谢您的 cmets!
猜你喜欢
  • 2011-11-16
  • 2018-12-09
  • 1970-01-01
  • 2013-12-15
  • 2015-01-19
  • 2013-06-08
  • 2012-04-20
  • 2011-03-02
  • 2012-06-10
相关资源
最近更新 更多