且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MySQL-如何检查START TRANSACTION是否处于活动状态

更新时间:2022-05-17 10:26:44

您可以创建一个函数,该函数将利用仅在事务内发生的错误:

You can create a function that will exploit an error which can only occur within a 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 ;

测试功能:

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;

结果:

@within_transaction | @out_of_transaction
--------------------|--------------------
                  1 |                   0

通过MariaDB,您可以使用@@in_transaction

With MariaDB you can use @@in_transaction