我需要在using()中照顾/关闭SQL连接吗? [英] Do I have to take care of opnening/closing sql connection within using()?

查看:92
本文介绍了我需要在using()中照顾/关闭SQL连接吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 using (IDbConnection conn = new SqlConnection(ConnectionString))
      {
        DataTable dtResult = null;
        try
        {
          IDbCommand cmd = conn.CreateCommand();
          cmd.CommandType = CommandType.Text;
          cmd.CommandText = query;

          IDbDataAdapter adapter = new SqlDataAdapter();
          adapter.SelectCommand = cmd;

          DataSet ds = new DataSet();

          adapter.Fill(ds);

          dtResult = ds.Tables[0];
          return dtResult;
        }
        catch (SqlException ex)
        {
          throw ex;          
        }
      }

在using()中使用sql server的最佳实践是什么?

What is the best practice to work with sql server within using()?

推荐答案

您需要打开连接,但无需关闭连接.  通常,无需先调用Close()就可以处置具有Close()方法并且也可以抛弃的对象(例如流和SqlConnections),您将获得相同的结果. 由于Dispose()是在using块的末尾调用的,因此您无需自己调用它.

You need to open connections but you don't need to close them.  Generally, objects which have a Close() method and are also disposable such as streams and SqlConnections can be disposed without calling Close() first and you'll get the same results.  Since Dispose() is called at the end of a using block, you don't need to call it yourself.

我还要指出,IDbCommand也是可浸入的,因此应将其使用包装在using块中.

I would also point out that IDbCommand is dipsosable too, so its use should be wrapped in a using block.

埃文


这篇关于我需要在using()中照顾/关闭SQL连接吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆