Bre*_*Bim 5 c# database idisposable
我有一个数据访问类的基类。此类实现IDisposable。这个基类包含IDbConnection并在构造函数中实例化它。
public class DALBase : IDisposable
{
protected IDbConnection cn;
public DALBase()
{
cn = new MySqlConnection(connString);
}
public void Dispose()
{
if (cn != null)
{
if (cn.State != ConnectionState.Closed)
{
try
{
cn.Close();
}
catch
{
}
}
cn.Dispose();
}
}
}
Run Code Online (Sandbox Code Playgroud)
从此类继承的类实际上访问数据库:
public class FooDAL : DALBase
{
public int CreateFoo()
{
// Notice that the cmd here is not wrapped in a using or try-finally.
IDbCommand cmd = CreateCommand("create foo with sql", cn);
Open();
int ident = int.Parse(cmd.ExecuteScalar().ToString());
Close();
cmd.Dispose();
return ident;
}
}
Run Code Online (Sandbox Code Playgroud)
使用FooDAL的类使用using模式来确保使用以下代码在FooDAL上调用Dispose:
using(FooDAL dal = new FooDAL())
{
return dal.CreateFoo();
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,即使没有将IDbCommand包裹在使用模式中或未进行最终尝试,这是否也可以确保正确处理IDbCommand?如果在命令执行期间发生异常会怎样?
另外,出于性能原因,在CreateFoo中实例化连接而不是在基类的构造函数中实例化连接会更好吗?
任何帮助表示赞赏。
鉴于连接是池化的,只需在 CreateFOO 方法中创建 MySqlConnection(使用 using 块)即可。
不必费心关闭它,因为它将在 using 块的末尾自动处理/关闭。
public int CreateFoo()
{
using (var cn = new MySqlConnection(connString))
{
// Notice that the cmd here is not wrapped in a using or try-finally.
using (IDbCommand cmd = CreateCommand("create foo with sql", cn))
{
cn.Open();
return int.Parse(cmd.ExecuteScalar().ToString());
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
939 次 |
最近记录: |