首页 > 代码库 > c#事务
c#事务
1.正常程序里的事务:
using (System.Transactions.TransactionScope ts = new TransactionScope())
{
try
{
//Sql语句
ts.Complete();//提交事务
}
catch (Exception e)
{
Logger.WriteLog(e.Message);
}
finally
{
ts.Dispose();//释放事务
}
}
2.sql语句中事务:
public void shiwu(){
try{
SqlConnection conn = new SqlConnection(SqlHelper.connectionString);
conn.Open();
SqlTransaction tran = null;
tran = conn.BeginTransaction();
SqlCommand cmd = new SqlCommand();
cmd.Transaction = tran;//挂起事务
cmd.Connection = conn;
sql_insert=sql;//sql语句
DbHelperSQL.PrepareCommand(cmd, conn, tran, sql_insert, null);
int val = cmd.ExecuteNonQuery();
tran.Commit();//执行成功 事务提交
}
catch(Exception e)
{
tran.Rollback();//报错的话 事务回滚
}
finally
{
conn.Close();//关闭连接
}
}