mysql implements commit and rollback instances of transactions
- 2020-06-19 11:50:42
- OfStack
The official syntax for mysql to create stored procedures is:
START TRANSACTION | BEGIN [WORK]
COMMIT [WORK] [AND [NO] CHAIN] [[NO] RELEASE]
ROLLBACK [WORK] [AND [NO] CHAIN] [[NO] RELEASE]
SET AUTOCOMMIT = {0 | 1}
The mysql transaction I'm showing here deals with the rollback of multiple SQL statements. For example, a transaction is started in a stored procedure, which inserts data into three tables at the same time. After each table is inserted, it needs to judge whether the operation is successful or not. If it is not successful, it needs to roll back. The important thing to note here is that collback for transactions cannot be used directly, so there is no possibility of rollback or unexpected errors.
So what we need is a conditional judgment, like loop, because MySql automatically commits by default, so we don't have to worry about the condition exiting after rollback without commit.
The specific mysql statement is as follows:
begin
loop_lable: loop
start transaction;
insert into table1(f_user_id) values(user_id);
if row_count() < 1 then
set @ret = -1;
rollback;
leave loop_label;
end if;
insert into table2(f_user_id) values(user_id);
if row_count() < 1 then
set @ret = -1;
rollback;
leave loop_label;
end if;
insert into table3(f_user_id) values(user_id);
if row_count() < 1 then
set @ret = -1;
rollback;
leave loop_label;
else
set @ret = 0;
commit;
leave loop_label;
end if;
end loop;
select @ret;
end