Is there any need to close a DbConnection if a using clause is used?(如果使用 using 子句,是否需要关闭 DbConnection?)
问题描述
<块引用>可能重复:
使用块会关闭数据库连接吗?
下面的db.Close()是不是不需要?
使用 (DbConnection db = GetDbConnection()){//做数据访问的东西//...db.Close();}
如果使用 using 子句,是否需要关闭 DbConnection?
不,如果使用 using 子句,是否不需要关闭 DbConnection?
和
是的,这里没有必要,因为当using
的范围结束时,connection会处理关闭和释放所有内存的意思.
由于DBConnection
实现了IDisposable
接口,所以DBConnection
的Dispose
方法中有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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果使用 using 子句,是否需要关闭 DbConnection?
基础教程推荐
- 将 XML 转换为通用列表 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30