复制代码 代码如下:
private static SqlConnection Cnn = new SqlConnection(DbConfig.ConnectionString);
#region 判读SqlConnection 是否开启连接 并开启
/// <summary>
/// 判读SqlConnection 是否开启连接 并开启
/// </summary>
/// <returns>返回SqlConnection</returns>
private static SqlConnection GetCnn()
{
if (Cnn.State == ConnectionState.Closed)
{
Cnn.Open();
}
return Cnn;
}
#endregion
#region 关闭数据库连接
/// <summary>
/// 关闭数据库连接
/// </summary>
public static void CloseCnn()
{
Cnn.Close();
}
#endregion
#region 产生一个事务并开始
/// <summary>
/// 产生一个事务并开始
/// </summary>
/// <returns>返回此事务</returns>
public static SqlTransaction BeginTransaction()
{
SqlTransaction tran = GetCnn().BeginTransaction();
return tran;
}
#endregion
复制代码 代码如下:
public bool test(int i,SqlTransaction tran)
{
string sql = "insert into [test]([item]) values(@i)";
SqlParameter[] paras=new SqlParameter[]{new SqlParameter("@i",i)};
return sqlhelper.ExecutenQuery(sql, paras, CommandType.Text, tran)>0;
}
复制代码 代码如下:
UserDAO userdao = new UserDAO();
public bool test()
{
using (SqlTransaction tran = SQLHelper.BeginTransaction())
{
try
{
userdao.test(2, tran);
userdao.test(3, tran);
tran.Commit(); return true;
}
catch
{
tran.Rollback();
return false;
}
finally
{
SQLHelper.CloseCnn();//关闭数据库连接
}
}
}
新闻热点
疑难解答
图片精选