2015-06-22 90 views
5

如何在SQL語句中有任何錯誤時啓動事務,系統將自動回滾這些更改?嘗試....在mysql中捕獲事務?

Transaction MySQL

PHP + MySQL transactions examples

在PHP

try { 
    // First of all, let's begin a transaction 
    $db->beginTransaction(); 

    // A set of queries; if one fails, an exception should be thrown 
    $db->query('first query'); 
    $db->query('second query'); 
    $db->query('third query'); 

    // If we arrive here, it means that no exception was thrown 
    // i.e. no query has failed, and we can commit the transaction 
    $db->commit(); 
} catch (Exception $e) { 
    // An exception has been thrown 
    // We must rollback the transaction 
    $db->rollback(); 
} 

如何重複邏輯沒有PHP,只有MYSQL

回答

2

這是我最後的工作在SQL與交易相關的,也許下面的代碼示例可以幫助你。該代碼是爲MS SQL服務器開發的,您可能需要爲MySQL服務器進行一些更改。

主要思想是在「try」和「transaction」子句中放置主查詢(可以是多個),然後如果查詢成功執行,則查詢將在數據庫中提交,否則在如果失敗,則在事務完全回滾之前,「catch」部分會引發錯誤。

BEGIN TRY 
    BEGIN TRANSACTION 
     --Insert Your Queries Here-- 
    COMMIT 
END TRY 
BEGIN CATCH 
    DECLARE @ErrorMessage NVARCHAR(4000); 
    DECLARE @ErrorSeverity INT; 
    DECLARE @ErrorState INT; 

    SELECT 
     @ErrorMessage = ERROR_MESSAGE(), 
     @ErrorSeverity = ERROR_SEVERITY(), 
     @ErrorState = ERROR_STATE(); 


    IF @@TRANCOUNT > 0 
    ROLLBACK 

    RAISERROR (@ErrorMessage, -- Message text. 
       @ErrorSeverity, -- Severity. 
       @ErrorState -- State. 
       ); 

END CATCH 
0

你可以寫多個查詢到MySQL過程/函數,可以保持交易就像下面給出的樣品。基本上,你聲明一個將調用回滾的錯誤處理程序。

PROCEDURE `myprocedure`() 
BEGIN 

.. Declare statements .. 

DECLARE EXIT HANDLER FOR SQLEXCEPTION 
BEGIN 
     .. set any flags etc eg. SET @flag = 0; .. 
     ROLLBACK; 
END; 

START TRANSACTION; 

    .. Query 1 .. 
    .. Query 2 .. 
    .. Query 3 .. 

COMMIT; 
.. eg. SET @flag = 1; .. 

END 

請參考下面的鏈接瞭解詳情

MySQL : transaction within a stored procedure

How can I use transactions in my MySQL stored procedure?