·举例:
------数据库中的事务
银行转账: 李四转500给张三
BEGIN
DECLARE @AccountMoney1 int;
DECLARE @AccountMoney2 int;
SET @AccountMoney1=0;
SET @AccountMoney2=0;
BEGIN TRAN --定义事物
UPDATE TEST
SET @AccountMoney1=AccountMoney=AccountMoney+500
WHERE AcountName='张三'
UPDATE TEST
SET @AccountMoney2=AccountMoney=AccountMoney-500
WHERE AcountName='李四'
PRINT @AccountMoney1;
PRINT @AccountMoney2;
IF(@AccountMoney1=@AccountMoney2)
COMMIT TRAN --提交事物
ELSE
ROLLBACK TRAN --回滚事物
END
-----------------------C#中的事务
/// <summary>
/// 本地事物
/// </summary>
public void LocaltionTransactionDemo()
{
int intResult = 0;
string strCon = "Data Source=.;Initial Catalog=DB_TRANS;Integrated Security=True";
string strSQL = @"UPDATE TEST
SET AccountMoney=AccountMoney+500
WHERE AcountName='张三'
UPDATE TEST
SET AccountMoney=AccountMoney-500
WHERE AcountName='李四'";
using (SqlConnection con = new SqlConnection(strCon))
{
con.Open();
SqlTransaction st = con.BeginTransaction(); //定义事物
SqlCommand com = new SqlCommand(strSQL, con);
com.Transaction = st; //事物赋值给SqlCommand
public void Demo1()
{
int intResult = 0;
string strCon = "Data Source=.;Initial Catalog=DB_TRANS;Integrated Security=True";
string strSQL = @"UPDATE TEST
SET AccountMoney=AccountMoney+500
WHERE AcountName='张三'";
using (SqlConnection con = new SqlConnection(strCon))
{
con.Open();
SqlCommand com = new SqlCommand(strSQL, con);
intResult = com.ExecuteNonQuery();
}
Console.WriteLine("执行影响的行数: {0}", intResult);
}
public void Demo2()
{
int intResult = 0;
string strCon = "Data Source=.;Initial Catalog=DB_TRANS;Integrated Security=True";
string strSQL = @"UPDATE TEST
SET AccountMoney=AccountMoney-500
WHERE AcountName='李四'";
using (SqlConnection con = new SqlConnection(strCon))
{
con.Open();
SqlCommand com = new SqlCommand(strSQL, con);
intResult = com.ExecuteNonQuery();
}
Console.WriteLine("执行影响的行数: {0}", intResult);
}