Automatic Rollback if COMMIT TRANSACTION is not reached

ぃ、小莉子 提交于 2019-11-27 13:38:58

No, transactions are not rolled back as soon as an error occurs. But you may be using a client-application which applies this policy.

For example, if you are using the mysql command-line client, then it normally stops executing when an error occurs and will quit. Quitting while a transaction is in progress does cause it to be rolled back.

When you are writing your own application, you can control the policy on rollback, but there are some exceptions:

  • Quitting (i.e. disconnecting from the database) always rolls back a transaction in progress
  • A deadlock or lock-wait timeout implicitly causes a rollback

Other than these conditions, if you invoke a command which generates an error, the error is returned as normal, and you are free to do whatever you like, including committing the transaction anyway.

You may use procedure to do this more effectively.
Transaction with Stored Procedure in MySQL Server

Rogerio de Moraes

Use Mysql stored procedure

   BEGIN

   DECLARE exit handler for sqlexception
      BEGIN
      ROLLBACK;
   END;

   DECLARE exit handler for sqlwarning
     BEGIN
     ROLLBACK;
   END;

   START TRANSACTION;

   INSERT INTO prp_property1 (module_name,environment_name,NAME,VALUE) VALUES ('','production','','300000');

   [ERROR]

   COMMIT;

   END

You can set if warning or error rollback, then you don't need delete, with transaction all entry is deleted.

I would like to add to what @MarkR already said. Error Handling, assuming InnoDB engine, happens as described in the Mysql Server Documentation

  • If you run out of file space in a tablespace, a MySQL Table is full error occurs and InnoDB rolls back the SQL statement.
  • A transaction deadlock causes InnoDB to roll back the entire transaction.
  • A duplicate-key error rolls back the SQL statement
  • A row too long error rolls back the SQL statement.
  • Other errors are mostly detected by the MySQL layer of code (above the InnoDB storage engine level), and they roll back the corresponding SQL statement

My understanding is also that when the Mysql session ends (when the php scripts ends), anything that is not committed is rolled back. I yet have to find a really reliable source to back this statement so do not take my word for it.

I've tested these three situations; mySQL does not roll back automatically.

A transaction deadlock causes InnoDB to roll back the entire transaction. A duplicate-key error rolls back the SQL statement A row too long error rolls back the SQL statement.

Only the affected records fail, the rest of the records succeed unless your application calls "rollback" explicitly.

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