mysql 5.1 signal an error to cause PDO exceptions

我是研究僧i 提交于 2020-01-07 03:39:13

问题


I know mysql 5.5 allows using SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Error: ...'; to raise a user defined error. And this error will stop an INSERT operation if it was put in the BEFORE INSERT TRIGGER on some tables. And it's also convenient for PDO to catch the PDOException and output the errorinfo() i.e. MESSAGE_TEXT defined in SIGNAL SQLSTATE.
However, the version of mysql on the server I rent is mysql 5.1. And I want to know how can I raise a user defined error with the features like the SIGNAL SQLSTATEMENT in mysql 5.5.

  1. interrupt a insert operation when it's in before insert trigger
  2. can be caught by PDO

I've found some topics on similar problems, and I've tried these:

  • call a nonexist procedure

    call `sp_raise_error`;

  • use a function to throw an error

https://blogs.oracle.com/svetasmirnova/entry/how_to_raise_error_in

Both can't be caught by PDO. So what's a solution? ( I tested on MySQL5.5 )


回答1:


If you use SIGNAL SQLSTATE in a lower version of MySQL (like 5.1), you will get a 1064 error. So, in order to use the function like SIGNAL SQLSTATE does, you can try the following steps.

1. Create Auxiliary Table Named "TBL_DUMMY"

CREATE TABLE IF NOT EXISTS `TBL_DUMMY`  
(
    `error` VARCHAR(256)
);

2. Create BEFORE INSERT Trigger on TBL_DUMMY

delimiter $$  
CREATE TRIGGER `TRIG_BI_DUMMY` BEFORE INSERT ON `TBL_DUMMY`  
    FOR EACH ROW
BEGIN  
    SET NEW = NEW.`error`;
END $$  

3. Create Procedure Named "SP_RAISE_ERROR"

delimiter $$  
CREATE PROCEDURE `SP_RAISE_ERROR` (IN P_ERROR VARCHAR(256))  
BEGIN  
    DECLARE V_ERROR VARCHAR(300);
    SET V_ERROR := CONCAT('[ERROR: ', P_ERROR, ']');
    INSERT INTO `TBL_DUMMY` VALUES (V_ERROR);
END $$

4. Usage

Just execute SP_RAISE_ERROR instead of SIGNAL SQLSTATE. For instance, CALL SP_RAISE_ERROR ('Password incorrect.') will throw an exception and the message is:

0 15:40:23 CALL SP_RAISE_ERROR ('Password incorrect.') Error Code: 1231. Variable 'new' can't be set to the value of '[ERROR: Password incorrect.]'.

And you can use it in procedures:

IF V_ID IS NOT NULL AND V_ID <> P_ID THEN  
    CALL `SP_RAISE_ERROR` ('Title duplicated.');
END IF; 

After that, you can extract error texts from the messages in an external program.



来源:https://stackoverflow.com/questions/18070473/mysql-5-1-signal-an-error-to-cause-pdo-exceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!