unit main;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, DB, ADODB, Grids, DBGrids, StdCtrls;

type
  TForm1 = class(TForm)
    ADOConnection1: TADOConnection;
    ADOTable1: TADOTable;
    DBGrid1: TDBGrid;
    DataSource1: TDataSource;
    btnBegin: TButton;
    btnRollBack: TButton;
    btnCommit: TButton;
    btnClose: TButton;
    procedure btnBeginClick(Sender: TObject);
    procedure btnRollBackClick(Sender: TObject);
    procedure btnCommitClick(Sender: TObject);
    procedure btnCloseClick(Sender: TObject);
    procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

//当用户单击“开始事务”按钮时，触发该事件
procedure TForm1.btnBeginClick(Sender: TObject);
begin
  //开始新事务
  with ADOConnection1 do
  begin
    if not InTransaction then
       BeginTrans;
    //设置按钮和DBGrid状态
    if InTransaction then
    begin
      btnCommit.Enabled := True;
      btnRollBack.Enabled := True;
      btnBegin.Enabled := False;
      //允许用户编辑
      DBGrid1.ReadOnly := False;
    end;
  end;
end;

//当用户单击“提交事务”按钮时，触发该事件
procedure TForm1.btnCommitClick(Sender: TObject);
begin
  //更新数据
   With ADOTable1 do
     if State = dsEdit then
        Post;

  //提交事务
  with ADOConnection1 do
  begin
    //保存所有修改
    if InTransaction then
       CommitTrans;
    //设置按钮和DBGrid状态
    if not InTransaction then
    begin
      btnBegin.Enabled := True;
      btnCommit.Enabled := False;
      btnRollBack.Enabled := False;
      //不允许用户编辑
      DBGrid1.ReadOnly := True;
   end;
  end;
end;


//当用户单击“回退事务”按钮时，触发该事件
procedure TForm1.btnRollBackClick(Sender: TObject);
begin
  //取消修改
   With ADOTable1 do
     if State = dsEdit then
        Cancel;

  //回滚事务
  with ADOConnection1 do
  begin
    //取消所有修改
    if InTransaction then
       RollbackTrans;
    //设置按钮和DBGrid状态
    if not InTransaction then
    begin
      btnBegin.Enabled := True;
      btnCommit.Enabled := False;
      btnRollBack.Enabled := False;
      //刷新数据
      With ADOTable1 do
      begin
        DisableControls;
        Refresh;
        CancelUpdates;
        EnableControls;
      end;
      //不允许用户编辑
      DBGrid1.ReadOnly := True;
    end;
  end;
end;


//当用户单击“关闭”按钮时，触发该事件
procedure TForm1.btnCloseClick(Sender: TObject);
begin
  Close;
end;

procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
var ret:Integer;
begin
  if ADOConnection1.InTransaction then
  begin
    ret := MessageBox(handle, '要退出程序，是否选择保存修改？',
               '数据保存', MB_YESNOCANCEL+MB_ICONQUESTION	);
    case ret of
      //保存修改
      IDYES: btnCommitClick(self);
      //不保存
      IDNO: btnRollBackClick(self);
      //取消操作
      IDCANCEL: CanClose := False;
    end;
  end;
end;

end.
