【问题标题】:try....catch in mysql for transaction?尝试....捕获 mysql 进行交易?
【发布时间】:2015-09-07 11:51:58
【问题描述】:

当SQL语句出现错误系统会自动回滚更改时,如何启动事务?

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的情况下重复逻辑

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    我们可以将多个查询写入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?

    【讨论】:

      【解决方案2】:

      这是我最后一篇与SQL事务相关的工作,也许下面的代码示例可以帮助到你。该代码是为 MS SQL 服务器 开发的。 请注意,您不能在 MySQL 服务器中使用它,因为 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
      

      【讨论】:

      • 这没有用,因为问题要求在 mysql 中使用 try/catch。
      猜你喜欢
      • 1970-01-01
      • 2011-03-25
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      • 2016-10-07
      • 2019-02-11
      • 2011-12-10
      • 1970-01-01
      相关资源
      最近更新 更多