How to execute transactions in MySQL?

在MySQL中执行事务可以通过以下步骤:

  1. Begin or start a transaction using the BEGIN or START TRANSACTION statement.
  2. Execute SQL statements in transactions, including INSERT, UPDATE, DELETE, and other operations.
  3. If all SQL statements are executed successfully, you can use the COMMIT statement to commit the transaction, making all operations take effect.
  4. If an error occurs or if you need to undo a previous operation, you can use the ROLLBACK statement to rollback the transaction, causing all operations to be undone.

For example, here is an example of performing a transaction in MySQL:

BEGIN; – Start transaction.

Update the balance in the accounts table by subtracting 100 from the current balance where the id is 1. – Perform SQL operation

Execute SQL operation to update the balance of account with ID 2 by adding 100.

submit transaction

In the example above, we begin a transaction with BEGIN, then perform two update operations, and finally commit the transaction with COMMIT. If the update operations are successful, all changes will take effect. If there is an error during the update operations, we can use ROLLBACK to roll back the transaction and undo all changes.

bannerAds