什么类要继承于IDisposable呢
public class SQLBase : IDisposable
{
private SqlConnection conn;
private SqlTransaction trans = null;
#region 释放资源
/// <summary>
/// 释放资源
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(true);
}
/// <summary>
/// 释放资源
/// </summary>
/// <param name="disposing"> </param>
protected virtual void Dispose(bool disposing)
{
if (!disposing)
{
return;
}
if (trans != null)// 如果
trans.Commit();
this.conn.Close();
}
#endregion
/// <summary>
/// 执行查询语句
/// </summary>
/// <param name="strSQL"> </param>
/// <param name="arrParameter"> </param>
/// <param name="CT"> </param>
/// <returns> </returns>
public int ExecuteNonQuery(string strSQL, SqlParameter[] arrParameter, CommandType CT)
{
using (SqlCommand cmd = new SqlCommand(strSQL, conn))
{
if (trans == null)
{
trans = conn.BeginTransaction(); ;
}
cmd.Transaction = trans;
cmd.CommandType = CT;
if (arrParameter != null)
{
foreach (SqlParameter sp in arrParameter)
{
cmd.Parameters.Add(sp);
}
}
try
{
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
catch (Exception ex)
{
trans.Rollback();
trans = null;
throw new Exception("执行" + strSQL + "发生错误,已经回滚事务,错误信息是:" + ex.Message);
}
}
}
}
比如这段代码,执行完毕了ExecuteNonQuery
不管是否正常还是异常 都会执行关闭数据库,异常的情况下还多个回滚事务。
{
private SqlConnection conn;
private SqlTransaction trans = null;
#region 释放资源
/// <summary>
/// 释放资源
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(true);
}
/// <summary>
/// 释放资源
/// </summary>
/// <param name="disposing"> </param>
protected virtual void Dispose(bool disposing)
{
if (!disposing)
{
return;
}
if (trans != null)// 如果
trans.Commit();
this.conn.Close();
}
#endregion
/// <summary>
/// 执行查询语句
/// </summary>
/// <param name="strSQL"> </param>
/// <param name="arrParameter"> </param>
/// <param name="CT"> </param>
/// <returns> </returns>
public int ExecuteNonQuery(string strSQL, SqlParameter[] arrParameter, CommandType CT)
{
using (SqlCommand cmd = new SqlCommand(strSQL, conn))
{
if (trans == null)
{
trans = conn.BeginTransaction(); ;
}
cmd.Transaction = trans;
cmd.CommandType = CT;
if (arrParameter != null)
{
foreach (SqlParameter sp in arrParameter)
{
cmd.Parameters.Add(sp);
}
}
try
{
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
catch (Exception ex)
{
trans.Rollback();
trans = null;
throw new Exception("执行" + strSQL + "发生错误,已经回滚事务,错误信息是:" + ex.Message);
}
}
}
}
比如这段代码,执行完毕了ExecuteNonQuery
不管是否正常还是异常 都会执行关闭数据库,异常的情况下还多个回滚事务。