使用mySQL进行隔离级别

时间:2015-06-05 01:00:07

标签: mysql transactions serializable isolation-level

我只是不知道如何形成这个查询。

问题:

如何使用MySQL查询隔离级别?

它应该像以下一样吗?

BEGIN;
SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE;
START TRANSACTION;

Select ....

COMMIT;

2 个答案:

答案 0 :(得分:2)

首先,您应将autocommit设置为0以在结束时运行提交:

SET AUTOCOMMIT = 0;

稍后,您应该设置隔离级别: (有关隔离级别的更多信息,请阅读https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html

SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE;

最后开发交易:

START TRANSACTION;
Select ....
/* all queries that you want */
COMMIT;

问候。

答案 1 :(得分:0)

问题1:How can I query for Isolation Level using MySQL?

MySQL 5.X

SELECT @@GLOBAL.TX_ISOLATION;  -- SERVER DEFAULT SETTING
SELECT @@SESSION.TX_ISOLATION; -- CURRENT SESSION SERVER SETTING

MySQL 8.X

SELECT @@GLOBAL.TRANSACTION_ISOLATION;  -- SERVER DEFAULT SETTING
SELECT @@SESSION.TRANSACTION_ISOLATION; -- CURRENT SESSION SERVER SETTING
  

注意:由于文档注释,我无法捕获事务期间的隔离更改:

     

Subsequent transactions revert to using the session value of the named characteristics.

问题2:How can I use this?

-- Capture your autocommit setting from your session.
SET @var_AC = (SELECT @@SESSION.AUTOCOMMIT);
-- SELECT @var_AC;

SET AUTOCOMMIT = 0; -- FORCE AUTOCOMMIT OFF
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; 
-- SET YOUR ISOLATION LEVEL FOR THE NEXT TRANSACTION

START TRANSACTION;
-- -- ADD YOUR CODE HERE
COMMIT;
-- IF NEEDED REVERT YOUR AUTOCOMMIT BACK TO WHAT IT WAS BEFORE
SET AUTOCOMMIT = @var_AC;

您也可以在“服务器默认设置”或当前会话上更改此设置,

SET @@GLOBAL.TRANSACTION_ISOLATION = 'transaction_characteristic'; -- Change for all FUTURE sessions.
SET @@SESSION.TRANSACTION_ISOLATION = 'transaction_characteristic'; -- Change for the Current Session.
SET @@TRANSACTION_ISOLATION = 'transaction_characteristic'; -- Change the next transaction setting.

有关TransactionsIsolation Levelshow they work.的更多信息

  

NOTE:   在所有存储的程序中,解析器将BEGIN [WORK]视为BEGIN ... END块的开始。

     

要在这种情况下开始transaction,请改用START TRANSACTION