Ste*_*one 7 mysql transactions autocommit
我注意到,START TRANSACTION自动COMMIT以前的查询.因为这个以及我在整个事务结束之前调用了几个存储过程的事实,我需要检查我是否在内部START TRANSACTION.阅读手册我明白autofommit在a里面设置为false START TRANSACTION,但它看起来不像这样.我写了以下程序:
CREATE DEFINER=`root`@`localhost` PROCEDURE `test_transaction`()
BEGIN
show session variables like 'autocommit';
start transaction;
show session variables like 'autocommit';
COMMIT;
show session variables like 'autocommit';
END
Run Code Online (Sandbox Code Playgroud)
但每个show session variables like 'autocommit';show autocommit = ON,而我预计第二个是autocommit = OFF.
如何检查我是否在里面START TRANSACTION?
我需要执行此检查,因为我有需要的procedure1 START TRANSACTION然后它调用也需要的procedure2 START TRANSACTION.但是我们假设我有第三个程序different_procedure,它也需要调用procedure2,但在这种情况下,different_procedure不会使用START TRANSACTION.在这种情况下,我需要procedure2来检查是否START TRANSACTION已启动.我希望这很清楚.
谢谢
您可以创建一个可以利用只能在事务中发生的错误的函数:
DELIMITER //
CREATE FUNCTION `is_in_transaction`() RETURNS int(11)
BEGIN
DECLARE oldIsolation TEXT DEFAULT @@TX_ISOLATION;
DECLARE EXIT HANDLER FOR 1568 BEGIN
-- error 1568 will only be thrown within a transaction
RETURN 1;
END;
-- will throw an error if we are within a transaction
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
-- no error was thrown - we are not within a transaction
SET TX_ISOLATION = oldIsolation;
RETURN 0;
END//
DELIMITER ;
Run Code Online (Sandbox Code Playgroud)
测试功能:
set @within_transaction := null;
set @out_of_transaction := null;
begin;
set @within_transaction := is_in_transaction();
commit;
set @out_of_transaction := is_in_transaction();
select @within_transaction, @out_of_transaction;
Run Code Online (Sandbox Code Playgroud)
结果:
@within_transaction | @out_of_transaction
--------------------|--------------------
1 | 0
Run Code Online (Sandbox Code Playgroud)
使用MariaDB,您可以使用 @@in_transaction
来自https://dev.mysql.com/doc/refman/5.5/en/implicit-commit.html:
事务不能嵌套。这是当您发出 START TRANSACTION 语句或其同义词之一时对任何当前事务执行隐式提交的结果。
我怀疑这个问题可以通过使用SET autocommit=0;而不是来解决START TRANSACTION;。如果autocommit已经是0,则不会有任何效果。
另请参阅在事务中设置 autocommit=0 是否会执行任何操作?