在mysql存储过程中使用TRY CATCH的异常

时间:2016-03-08 12:18:36

标签: mysql stored-procedures

以下是我试图捕获异常的过程,如果存储过程中有任何内容

DROP PROCEDURE IF EXISTS test;

DELIMITER //

CREATE PROCEDURE test( IN contextFilter TEXT)
   BEGIN TRY


  set  @sub_query = 'SELECT id from test_table';

   PREPARE stmt_query FROM @sub_query;
      SELECT @sub_query;
                EXECUTE stmt_query;
                DEALLOCATE PREPARE stmt_query;

   END TRY //
   BEGIN CATCH
    SELECT ERROR_NUMBER() AS ErrorNumber,ERROR_MESSAGE() AS ErrorMessage;
  END CATCH

 DELIMITER ;

当我尝试获取存储过程时,我收到以下异常

source /home/test.sql;
Query OK, 0 rows affected (0.01 sec)

ERROR 1064 (42000) at line 5 in file: '/home/test.sql': You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'set  @sub_query = 'SELECT id from test_table';

   PREPARE stmt_query FROM @' at line 5
ERROR 1064 (42000) at line 17 in file: '/home/test.sql': You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CATCH
    SELECT ERROR_NUMBER() AS ErrorNumber,ERROR_MESSAGE() AS ErrorMessage;
' at line 1

2 个答案:

答案 0 :(得分:3)

在mySql中,没有像Java那样的try... catch块。您可以通过错误处理来处理错误吗?

语法

DECLARE handler_action HANDLER
    FOR condition_value [, condition_value] ...
    statement

handler_action:
    CONTINUE
  | EXIT
  | UNDO

condition_value:
    mysql_error_code
  | SQLSTATE [VALUE] sqlstate_value
  | condition_name
  | SQLWARNING
  | NOT FOUND
  | SQLEXCEPTION

handler_action值指示执行处理程序语句后处理程序执行的操作:

CONTINUE :继续执行当前程序。

EXIT :对于声明处理程序的BEGIN ... END复合语句,执行终止。即使条件发生在内部块中也是如此。

UNDO :不支持。

有关详细信息,请转到Official网站

答案 1 :(得分:0)

上面的帖子对我有所帮助,但我仍然必须自己做一些研究。为了提供完整的示例,您可以在下面看到。这段代码将声明一个用于“捕获” SQLException的处理程序,然后在发生这种情况时退出。

DROP PROCEDURE IF EXISTS `SP_TEST`;
DELIMITER //
CREATE PROCEDURE `SP_TEST`()
BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION 
    BEGIN 
        GET DIAGNOSTICS CONDITION 1 @p1 = RETURNED_SQLSTATE, @p2 = MESSAGE_TEXT;
        SELECT CONCAT(@p1, ':', @p2);
    END;

    SELECT FAKE_COLUMN FROM MY_TABLE;
END //

CALL SP_TEST;

这在mySQL 5.7版中有效,希望对您有所帮助。