MySQL improves the buffer for reading abnormal errors (MySQL5.6)
What is an error buffer?
In MySQL, the Error Buffer only records the last error. If a new error is generated, the old one will be overwritten. If you want to know what errors are generated, you must follow "show warnings" or "show errors" after each statement that may have errors ". The simplest way is to redirect the output result to the custom log file, so that it can be conveniently viewed later. If you want to view these errors at any time, you must use the APIS provided by MySQL.
Since the emergence of the revolutionary MySQL 5.6 version, the problem has been preliminarily solved. Although it is far from what we think.
MySQL 5.6 provides the get diagnostic statement to get the content of the Error Buffer, and then output the content to variables in different range fields, so that we can flexibly perform subsequent operations.
Next, let's look at an example.
The target table structure is:
- CREATE TABLE'T_ datetime '(
- 'Id'Int(11)NOT NULL,
- 'Log _ time'Timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
- 'End _ time' datetimeNOT NULL,
- PRIMARY KEY('Id ')
- ) ENGINE = InnoDBDEFAULTCHARSET = utf8
The Stored Procedure Code is:
- DELIMITER $
- USE 'new _ t' $
- DROP PROCEDUREIf exists 'SP _ do_update '$
- CREATEDEFINER = 'root' @ 'localhost'PROCEDURE'SP _ do_update '(
- INF_idINT,
- INF_log_timeVARCHAR(255 ),
- INF_end_timeVARCHAR(255)
- )
- BEGIN
- DECLAREI _con1 TINYINTDEFAULT0;
- DECLAREI _codeCHAR(5)DEFAULT '123';
- DECLAREI _msg TEXT;
- DECLAREI _rowsINT;
- DECLAREI _con1 CONDITIONFOR1048;-- This error code indicates that the field cannot be NULL.
- DECLARE CONTINUEHANDLERFORI _con1
- BEGIN
- SETI _con1 = 1;
- Get diagnostics CONDITION 1
- I _code = returned_sqlstate, I _msg = message_text;
- END;
- UPDATET_datetime
- SETLog_time = IFNULL (f_log_time,NULL),
- End_time = IFNULL (f_end_time,NULL)
- WHEREId = f_id;
- IF I _con1 = 0THEN
- Get diagnostics I _rows = ROW_COUNT;
- SET@ I _result = CONCAT ("Update succeeded, affected", I _rows,'.');
- ELSE
- SET@ I _result = CONCAT ('Update failed, error code is 1042, related message is', I _msg,'.');
- ENDIF;
- SELECT@ I _result;
- END$
- DELIMITER;
After the above stored procedure is completed, the error information can be saved to the SESSION variable @ I _result. This facilitates the subsequent output.
- CALL sp_do_update (1, NOW (), DATE_ADD (NOW (), INTERVAL 1DAY));
- Result.
- UpdateSucceeded, affected 1.
- CALL sp_do_update (1,NULL,NULL);
- Result.
- UpdateFailed, error codeIs1042, related messageIs Column 'Log _ time'Cannot beNull.