mysql + unidac 使用事务例子
//备注:mysql必须是使用innoDB引擎才支持事务功能,否则以下事务相关代码将失效。//SQL SERVER和Oracle还没试,明天回公司试了再发代码。procedure TForm1.btn1Click(Sender: TObject); var i, j: Integer; begin UniConnection1.Connect; try try UniTransaction1.Connections[0].StartTransaction; UniQuery1.Params.Clear; UniQuery1.SQL.Text := 'insert into user (username,password)values(:username, :password)'; UniQuery1.Params.ParamByName('username').Value := 'eboy'; UniQuery1.Params.ParamByName('password').Value := '1111'; UniQuery1.ExecSQL; //如果不使用事务,这条将插入进去 UniQuery1.Params.Clear; UniQuery1.SQL.Text := 'insert into user (username,password)values(:username, :password)'; UniQuery1.Params.ParamByName('username').Value := 'frr'; UniQuery1.Params.ParamByName('password').Value := '123'; UniQuery1.ExecSQL; //如果不使用事务,这条将插入进去 UniQuery1.Params.Clear; UniQuery1.SQL.Text := 'insert into user (username,password)values(:username, :password)'; UniQuery1.Params.ParamByName('username').Value := 'lj'; UniQuery1.Params.ParamByName('password').Value := '880414'; UniQuery1.ExecSQL; //如果不使用事务,这条将插入进去 UniQuery1.Params.Clear; UniQuery1.SQL.Text := 'insert into user (username,password)values(:username, :password)'; UniQuery1.Params.ParamByName('username').Value := 'lj'; UniQuery1.Params.ParamByName('password').IsNull; //字段设为not null,所以这里会出错 UniQuery1.ExecSQL; //开启事务后,上面的三条都将回滚 UniTransaction1.Connections[0].Commit; except on e: Exception do begin UniTransaction1.Connections[0].Rollback; ShowMessage(e.Message); end; end; finally UniConnection1.Disconnect; end; end;