Home  >  Article  >  Database  >  mysql实现事务的提交和回滚实例_MySQL

mysql实现事务的提交和回滚实例_MySQL

WBOY
WBOYOriginal
2016-06-01 13:08:35857browse

mysql创建存储过程的官方语法为:

复制代码 代码如下:
START TRANSACTION | BEGIN [WORK]
COMMIT [WORK] [AND [NO] CHAIN] [[NO] RELEASE]
ROLLBACK [WORK] [AND [NO] CHAIN] [[NO] RELEASE]
SET AUTOCOMMIT = {0 | 1}

我这里要说明的mysql事务处理多个SQL语句的回滚情况。比如说在一个存储过程中启动一个事务,这个事务同时往三个表中插入数据,每插完一张表需要判断其是否操作成功,如果不成功则需要回滚,最后一张表判断其插入成功之后commit。这里需要注意的是不能直接使用事务的collback,这样是不能实现回滚的或者说可能出现意外的错误。

那么我们需要的是一个条件判断,比如loop,因为MySql默认是会自动提交的,所以我们不用担心rollback之后条件退出而没有commit。

具体mysql语句如下:

复制代码 代码如下:
begin
 loop_lable: loop
  start transaction;
   insert into table1(f_user_id) values(user_id);
  if row_count()     set @ret = -1;  
    rollback; 
    leave loop_label;
  end if;
  insert into table2(f_user_id) values(user_id);
 if row_count()   set @ret = -1; 
    rollback; 
   leave loop_label;
  end if;
   insert into table3(f_user_id) values(user_id);
  if row_count()     set @ret = -1; 
    rollback; 
    leave loop_label;
  else 
    set @ret = 0; 
    commit; 
    leave loop_label;
  end if;
  end loop;
  select @ret;
end 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn