2015-06-22 16 views
5

Come posso avviare una transazione quando c'è qualche errore nelle istruzioni SQL il sistema eseguirà il rollback delle modifiche automaticamente?try .... catch in mysql per la transazione?

Transaction MySQL

PHP + MySQL transactions examples

in 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(); 
} 

come ripetere la logica, senza PHP, solo MySQL

risposta

2

Questo è il mio ultimo lavoro relativo a transazioni in SQL, forse il codice di esempio qui sotto può aiutarti. Il codice è stato sviluppato per MS SQL Server e potrebbe essere necessario cambiarlo un po 'per il server MySQL.

L'idea principale è posizionare la query principale (che può essere più di una) all'interno delle clausole "try" e "transaction", quindi se la query viene eseguita correttamente, quindi la query verrà inserita nel database, altrimenti in In caso di errore, verrà generato un errore nella sezione "catch" prima che la transazione venga completamente ripristinata.

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

È possibile scrivere le query multiple nel MySQL procedura/funzione e può mantenere la transazione come con l'esempio indicato di seguito. Fondamentalmente, si dichiara un gestore di errori che chiamerà il rollback.

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 

prega di consultare i link di seguito per maggiori dettagli

MySQL : transaction within a stored procedure

How can I use transactions in my MySQL stored procedure?