MySQL Advanced Features-transaction processing

Source: Internet
Author: User

To use transactions in MySQL, you first need to create a table that uses a transaction table type, such as BDB = Berkeley db or InnoDB.

CREATE TABLE account (
account_id BIGINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
balance DOUBLE
) TYPE = InnoDB;

To use transactions on a transaction table, you must first turn off autocommit:

SET autocommit = 0;

Transactions begin with the BEGIN command:

BEGIN;

The MySQL client is now in the context of server-related things. Any changes made to the transaction table will not be permanent until they are submitted.

UPDATE account SET balance = 50.25 WHERE account_id = 1;

UPDATE account SET balance = 100.25 WHERE account_id = 2;

After making all the changes, use the commit command to complete the transaction:

COMMIT;

Of course, the real advantage of transaction processing is that it manifests itself in the execution of an error in the second statement, which can be rolled back if the entire transaction is terminated before committing:

ROLLBACK;

Here is another example of a direct mathematical operation via MySQL:

SELECT @first := balance FROM account WHERE account_id = 1;
SELECT @second := balance FROM account WHERE account_id = 2;
UPDATE account SET balance = @first - 25.00 WHERE account_id = 1;
UPDATE account SET balance = @second + 25.00 WHERE account_id = 2;

In addition to the commit command, the following command automatically ends the current transaction:

ALTER TABLE
BEGIN
CREATE INDEX
DROP DATABASE
DROP TABLE
LOCK TABLES
RENAME TABLE
TRUNCATE
UNLOCK TABLES

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.