Home > Database > Mysql Tutorial > MySQL高级特性----事务处理_MySQL

MySQL高级特性----事务处理_MySQL

WBOY
Release: 2016-06-01 14:12:10
Original
1235 people have browsed it

  要使用MySQL中的事务处理,首先需要创建使用事务表类型(如BDB = Berkeley DB或InnoDB)的表。
  
  CREATE TABLE account (
  account_id BIGINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
  balance DOUBLE
  ) TYPE = InnoDB;
  
  要在事务表上使用事务处理,必须要首先关闭自动提交:
  
  SET AUTOCOMMIT = 0;
  
  事务处理以BEGIN命令开始:
  
  BEGIN;
  
  现在mysql客户处在于服务器相关的事物上下文中。任何对事务表所做的改变在提交之前不会成为永久性的改变。
  
  UPDATE ACCOUNT SET balance = 50.25 WHERE account_id = 1;
  UPDATE ACCOUNT SET balance = 100.25 WHERE account_id = 2;
  
  在做出所有的改变之后,使用COMMIT命令完成事务处理:
  
  COMMIT;
  
  当然,事务处理的真正优点是在执行第二条语句发生错误时体现出来的,若在提交前终止整个事务,可以进行回滚操作:
  
  ROLLBACK;
  
  下面是另一个例子,通过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;
  
  除了COMMIT命令外,下列命令也会自动结束当前事务:
  
  ALTER TABLE
  BEGIN
  CREATE INDEX
  DROP DATABASE
  DROP TABLE
  LOCK TABLES
  RENAME TABLE
  TRUNCATE
  UNLOCK TABLES
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template