MySQL - How to check if START TRANSACTION is active

前端 未结 2 1909
鱼传尺愫
鱼传尺愫 2021-01-11 17:03

I have noticed that START TRANSACTION automatically COMMIT the previous queries. Because of this and the fact that I have several stored procedure

相关标签:
2条回答
  • 2021-01-11 17:43

    From https://dev.mysql.com/doc/refman/5.5/en/implicit-commit.html:

    Transactions cannot be nested. This is a consequence of the implicit commit performed for any current transaction when you issue a START TRANSACTION statement or one of its synonyms.

    I suspect that the problem can be solved by using SET autocommit=0; instead of START TRANSACTION;. If autocommit is already 0, it will have no effect.

    See also Does setting autocommit=0 within a transaction do anything?

    0 讨论(0)
  • 2021-01-11 18:01

    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 ;
    

    Test the function:

    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;
    

    Result:

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

    With MariaDB you can use @@in_transaction

    0 讨论(0)
提交回复
热议问题