在数据库连接上创建事务处理对象,然后调用事务处理对象来提交事务或回滚事务。简单的代码:
private void button1_click(object sender, system.eventargs e)
{
sqlconnection conn = new sqlconnection(data source=192.168.2.200;uid=sa; password=;database = haierhr);
conn.open();
//启用事务
sqltransaction tran = conn.begintransaction();
sqlcommand cmd = new sqlcommand();
cmd.connection = conn;
cmd.transaction = tran;
try
{
cmd.commandtext = update hrrollmain set totalmember=totalmember-100 where rollid = '2005070101';
cmd.executenonquery();
cmd.commandtext = update hrrollsum set totalsummember=totalsummember+100 where rollsumid = '20050701';
cmd.executenonquery();
tran.commit();
messagebox.show(事务提交成功!);
}
catch(exception ex)
{
tran.rollback();
messagebox.show(error!+ex.message);
}
}
更多信息请查看IT技术专栏