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?
基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
