sql事务、ado事务

sql server事务
begin try
begin transaction --开始事务
update UserInfo set UserName='你好' where UserId=2
update UserInfo set UserAge='你好' where UserId=3
commit transaction --提交事务
end try

begin catch
rollback transaction --回滚事务
end catch

ado 事务
第一种写法
string str ="连接数据库";
using(SqlConnection conn =new SqlConnection(str))
{
using(SqlCommand cmd=conn.CreateCommand())
{
conn.Open();
SqlTransaction trans = conn.BeginTranscation();
//创建事务对象
try
{
cmd.CommandText = @"update UserInfo set UserName='你好' where UserId=2
update UserInfo set UserAge='你好' where UserId=3";
cmd.Transaction = trans;
cmd.ExecuteNonQuery();

SqlCommand cmd2 =conn.CreateCommand();
cmd2.CommandText = @"update UserInfo set UserAge=UserAge+1 where UserId=4
cmd2.Transaction = trans;
cmd2.ExecuteNonQuery();
}
catch(Exception ex)
{
trans.Rollback();//回滚事务
}
}
}
第二种写法
添加引用 System.Transactions
try
{
using(TransactionScope scope=new (TransactionScope ())
{
string str ="连接数据库";
using(SqlConnection conn =new SqlConnection(str))
{
using(SqlCommand cmd=conn.CreateCommand())
{
conn.Open();

cmd.CommandText = @"update UserInfo set UserName='你好' where UserId=2
update UserInfo set UserAge='你好' where UserId=3";
cmd.ExecuteNonQuery();
}
}
scope.Complete();//提交事务
}
}
catch(Exception ex)
{

}

原文地址:https://www.cnblogs.com/jinjingBlog/p/9804125.html