Example of defining MySQL transactions

Source: Internet
Author: User

The MySQL transaction should be defined by every MySQL database user. The following describes how to define MySQL transactions, which is helpful to you.

By default, MySQL runs a COMMIT statement after each SQL statement is executed to effectively separate each statement into a transaction.
In complex application scenarios, this method cannot meet the requirements.
To open a transaction and allow execution of multiple statements before COMMIT and ROLLBACK, we need to do the following two steps:
1. Set the autocommit attribute of MySQL to 0. The default value is 1.
2. Use the start transaction statement to explicitly open a TRANSACTION.

If a TRANSACTION has been opened, SET autocommit = 0 does not work, because start transaction implicitly commits all the current changes in the session, ends the existing TRANSACTION, and opens a new TRANSACTION.

Example of a stored procedure using the set autocommit statement:

 
 
  1. CREATE PROCEDURE tfer_funds      
  2.      (from_account int, to_account int, tfer_amount numeric(10,2))      
  3. BEGIN      
  4.      SET autocommit=0;      
  5.      
  6.      UPDATE account_balance SET balancebalance=balance-tfer_amount WHERE account_id=from_account;      
  7.      
  8.      UPDATE account_balance SET balancebalance=balance+tfer_amount WHERE account_id=to_account;      
  9.      
  10.      COMMIT;      
  11. END;    

The preceding describes how to define MySQL transactions.

Mysql Stored Procedure FAQs

Example of creating a MySQL Stored Procedure

Mysql Stored Procedure Call Method

Use of mysql ifnull Functions

Learn more about MySQL GROUP_CONCAT Functions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.