由网友(孤单一辈子°)分享简介:我使用看起来像这样经常的模式。我不知道如果这是正常的,或者如果有,我不申请在这里的最佳实践。我特别想知道,在抛出一个异常的情况下是code,我在finally块足以确保连接适当关闭?公共类SomeDataClass:IDisposable的{私人的SqlConnection _conn;//构造函数和方法私人DoSo...
我使用看起来像这样经常的模式。我不知道如果这是正常的,或者如果有,我不申请在这里的最佳实践。
我特别想知道,在抛出一个异常的情况下是code,我在finally块足以确保连接适当关闭?
公共类SomeDataClass:IDisposable的
{
私人的SqlConnection _conn;
//构造函数和方法
私人DoSomethingWithTheSqlConnection()
{
//一些code排除为简便起见,
尝试
{
使用(CMD的SqlCommand =新的SqlCommand(SqlQuery.CountSomething,_SqlConnection))
{
_SqlConnection.Open();
countOfSomething = Convert.ToInt32(cmd.ExecuteScalar());
}
}
最后
{
//这是最好的方法是什么?
如果(_SqlConnection.State == ConnectionState.Closed)
_SqlConnection.Close();
}
//一些code排除为简便起见,
}
公共的Dispose()
{
_conn.Dispose();
}
}
解决方案
包装你的数据库处理code里面的使用
使用(SqlConnection的康恩=新的SqlConnection(...))
{
//在这里不管发生什么事,连接
//在末端布置的(闭)。
}
I use a pattern that looks something like this often. I'm wondering if this is alright or if there is a best practice that I am not applying here.
Specifically I'm wondering; in the case that an exception is thrown is the code that I have in the finally block enough to ensure that the connection is closed appropriately?
public class SomeDataClass : IDisposable
{
private SqlConnection _conn;
//constructors and methods
private DoSomethingWithTheSqlConnection()
{
//some code excluded for brevity
try
{
using (SqlCommand cmd = new SqlCommand(SqlQuery.CountSomething, _SqlConnection))
{
_SqlConnection.Open();
countOfSomething = Convert.ToInt32(cmd.ExecuteScalar());
}
}
finally
{
//is this the best way?
if (_SqlConnection.State == ConnectionState.Closed)
_SqlConnection.Close();
}
//some code excluded for brevity
}
public Dispose()
{
_conn.Dispose();
}
}
解决方案
Wrap your database handling code inside a "using"
using (SqlConnection conn = new SqlConnection (...))
{
// Whatever happens in here, the connection is
// disposed of (closed) at the end.
}
相关推荐
最新文章