using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
/*事务是一组被当作一个单元的操作,它们在执行时要么全部成功,要么全部失败。
例如转帐操作
事务的两个层次
数据库级的事务
ADO.NET事务
如果在某个操作中需要对数据库进行多次更新,则必须使用事务。
SqlTransaction myTransaction
=myConnection.BeginTransaction();
try
{ ...
myCommand = new OleDbCommand(cmdstr, myConnection,myTransaction);
...
myTransaction.Commit();
}
catch (Exception es)
{
myTransaction.Rollback();
}
*/
namespace Transaction
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String connectionString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
SqlConnection myconn = new SqlConnection(connectionString);
try
{
myconn.Open();
SqlTransaction myTransaction = myconn.BeginTransaction();//新建一个事务
try
{
string cmdstr = "update Account set money=money-100 where Id='1'";
SqlCommand mycmd = new SqlCommand(cmdstr,myconn,myTransaction);
mycmd.ExecuteNonQuery();
throw new Exception();//抛出异常,会直接被catch捕获,处理
string cmdstr2="update Account set money=money+100 where Id='2'";
SqlCommand mycmd1 = new SqlCommand(cmdstr2, myconn, myTransaction);
mycmd1.ExecuteNonQuery();
myTransaction.Commit();//只有执行这句后数据库里面的数据才有可能会改变
}
catch(Exception ee)
{
myTransaction.Rollback();//进行回滚
MessageBox.Show("转账失败,正在回滚!");
}
myconn.Close();
}
catch (Exception ex)
{
MessageBox.Show("数据库连接失败!");
}
}
}
}