如果使用 using 子句,是否需要关闭 DbConnection? [英] Is there any need to close a DbConnection if a using clause is used?

查看:17
本文介绍了如果使用 using 子句,是否需要关闭 DbConnection?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

可能重复:
使用块会关闭数据库连接吗?

下面的db.Close()是不是不需要?

使用 (DbConnection db = GetDbConnection()){//做数据访问的东西//...db.Close();}

解决方案

如果使用 using 子句,是否需要关闭 DbConnection?

不,如果使用 using 子句,是否不需要关闭 DbConnection?

是的,这里没有必要,因为当using的范围结束时,connection会处理关闭和释放所有内存的意思.

由于DBConnection实现了IDisposable接口,所以DBConnectionDispose方法中有close函数.p>

但如果有些行在关闭行之后,那么它很有用

使用 (DbConnection db = GetDbConnection()){//做数据访问的东西//...db.Close();//无用}

但这里有用

使用 (DbConnection db = GetDbConnection()){//做数据访问的东西//...db.Close();//有用//更多代码}

在这种情况下你可以这样做

使用 (DbConnection db = GetDbConnection()){//做数据访问的东西//...}//之前在 using 部分中的更多代码.

Possible Duplicate:
Will a using block close a database connection?

Is db.Close() unnecessary in the following?

using (DbConnection db = GetDbConnection())
{
   // do data-access stuff
   // ...

   db.Close();
}

解决方案

Is there any need to close a DbConnection if a using clause is used?

No, there is no need to close a DbConnection if a using clause is used?

and

Yes it is unnecessary in here because when scope of using ends, connection will dispose meaning closing and releasing all memory.

Since DBConnection implements IDisposable interface, close function is there in the Dispose method of DBConnection.

But if some lines are after close line then it is useful

using (DbConnection db = GetDbConnection())
{
  // do data-access stuff
  // ...

  db.Close(); //Useless
}

But here it is useful

using (DbConnection db = GetDbConnection())
{
  // do data-access stuff
  // ...

  db.Close(); //Useful

 // Some more code
}

In that case you can do

using (DbConnection db = GetDbConnection())
{
  // do data-access stuff
  // ...

}

// Some more code which was previously inside using section.

这篇关于如果使用 using 子句,是否需要关闭 DbConnection?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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