我们可以将check
(某种)放到 -
仅在操作成功完成时检查数据是否已提交到数据库。
如果交易失败,应回滚数据。
DELIMITER $$
CREATE PROCEDURE `sp_fail`()
BEGIN
DECLARE `_rollback` BOOL DEFAULT 0;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET `_rollback` = 1;
START TRANSACTION;
UPDATE customer SET age= 20 WHERE name='stark';
UPDATE customer SET age= 20 WHERE name='brian'; -- fail as there is no name as brian in the table customer
IF `_rollback` THEN
SELECT 'The transaction has failed' AS 'Result';
ROLLBACK;
ELSE
SELECT 'The transaction was successful' AS 'Result';
COMMIT;
END IF;
END$$
DELIMITER ;
它的自我修改版本的stackoverflow本身的答案之一。我正在考虑使用它来解决上面提到的点,但当我调用该过程时,调用成功运行,但没有行受影响。为什么? 提前谢谢。
答案 0 :(得分:0)
mysql中有Autocommit属性。您需要设置AUTOCOMMIT = 0(这会将autocommit设置为false),之后您可以根据您的条件在查询结束时发出COMMIT或ROLLBACK。
1. INSERT INTO table_name ...;
2. COMMIT; -- confirm your changes
OR
3. ROLLBACK; -- undo your changes