我有以下ado.net代码,如果我已经使用使用来包装我的DBCommand,是否必须明确关闭底层连接?
谢谢,
public static void ExecuteSQL(int Id)
{
Database db;
const string sqlCommand = "Stored Procedure Name";
try
{
db = DatabaseFactory.CreateDatabase();
using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand))
{
db.AddInParameter(dbCommand, "p_Id", DbType.Int32, Id);
db.ExecuteNonQuery(dbCommand);
**//do I have to close connection explicitely here??**
if (dbCommand.Connection.State != ConnectionState.Closed)
{
dbCommand.Connection.Close();
}
dbCommand.Connection.Dispose();
}
}
catch (Exception ex)
{
Logger.Log.Error(ex.StackTrace, ex);
throw;
}
}
答案 0 :(得分:5)
是的,如果您在using
区块中包含的所有内容都是DbCommand
,那么您将必须明确关闭DbConnection
,因为您目前在你的代码中做。但是,只需拨打Dispose
即可。您无需同时拨打Close
和Dispose
。
答案 1 :(得分:2)
http://www.willydev.net/descargas/WillyDev_EntLib_TestGuide.pdf
应用程序块在完成后关闭数据库连接。例如,ExecuteNonQuery方法的实现包括using语句。 using语句获取资源,执行语句并处理资源。在这种情况下,资源是数据库连接。对于ExecuteReader方法,应用程序块使用Command-Behavior.CloseConnection方法在阅读器关闭后关闭连接。
答案 2 :(得分:1)
这篇文章很老了,但是我回答说如果我们在EnterpriseLibrary中使用这个块,我确定连接已经关闭(代码块中的类和方法名称让我想到这一点)。 提出问题的人,以及谁回答应该明确考虑我们是否在谈论EnterbriseLibrary。 我使用finally块进行了测试,并且YES,在使用带有DbCommand的块后自动关闭连接。
答案 3 :(得分:-1)
不,你没有。
一旦命中结束使用块,就会为你调用dispose。