MySQL トランザクション
Rev.4を表示中。最新版はこちら。
トランザクションを使うと複数のクエリをまとめて処理することができる。処理の途中でエラーになった場合は変更内容を元に戻す(RollBack)ことができる。トランザクションはInnoDBテーブルにしか使えない(デフォルトはMyISAM)。
InnoDBテーブルの作成
新規に作るテーブルをInnoDBにするには、以下のようにする。mysql> CREATE TABLE friends (id SERIAL, name VARCHAR(30)既存のテーブルのInnoDBに変更する場合は以下のとおり。
NOT NULL, address VARCHAR(100), birthday DATETIME) TYPE=InnoDB;
mysql> ALTER TABLE friends TYPE = INNODB;
トランザクションの開始
行単位のロック
スレッドA | スレッドB |
---|---|
mysql> select id,name from friends; +----+--------+ | id | name | +----+--------+ | 1 | tomita | +----+--------+ 1 row in set (0.00 sec) | mysql> select id,name from friends; +----+--------+ | id | name | +----+--------+ | 1 | tomita | +----+--------+ 1 row in set (0.00 sec) |
mysql> START TRANSACTION; Query OK, 0 rows affected (0.00 sec) | |
mysql> INSERT INTO friends (name, address, birthday) VALUES("suzuki", "Kamata xxxx", "2006-05-13 12:34:56"); Query OK, 1 row affected (0.00 sec) | |
mysql> select id,name from friends; +----+--------+ | id | name | +----+--------+ | 1 | tomita | | 2 | suzuki | +----+--------+ 2 rows in set (0.00 sec) | mysql> select id,name from friends; +----+--------+ | id | name | +----+--------+ | 1 | tomita | +----+--------+ 1 row in set (0.00 sec) |
mysql> COMMIT; Query OK, 0 rows affected (0.01 sec) | |
mysql> select id,name from friends; +----+--------+ | id | name | +----+--------+ | 1 | tomita | | 2 | suzuki | +----+--------+ 2 rows in set (0.00 sec) | mysql> select id,name from friends; +----+--------+ | id | name | +----+--------+ | 1 | tomita | | 2 | suzuki | +----+--------+ 2 rows in set (0.00 sec) |
スレッドA | スレッドB |
---|---|
mysql> select id,name from friends; +----+--------+ | id | name | +----+--------+ | 1 | tomita | | 2 | suzuki | +----+--------+ 2 rows in set (0.00 sec) | mysql> select id,name from friends; +----+--------+ | id | name | +----+--------+ | 1 | tomita | | 2 | suzuki | +----+--------+ 2 rows in set (0.00 sec) |
mysql> START TRANSACTION; Query OK, 0 rows affected (0.00 sec) | |
mysql> INSERT INTO friends (name, address, birthday) VALUES("tanaka", "Kamata xxxx", "2006-05-13 12:34:56"); Query OK, 1 row affected (0.00 sec) | |
mysql> select id,name from friends; +----+--------+ | id | name | +----+--------+ | 1 | tomita | | 2 | suzuki | | 3 | tanaka | +----+--------+ 3 rows in set (0.00 sec) | mysql> select id,name from friends; +----+--------+ | id | name | +----+--------+ | 1 | tomita | | 2 | suzuki | +----+--------+ 2 rows in set (0.00 sec) |
mysql> ROLLBACK; | |
mysql> select id,name from friends; +----+--------+ | id | name | +----+--------+ | 1 | tomita | | 2 | suzuki | +----+--------+ 2 rows in set (0.00 sec) | mysql> select id,name from friends; +----+--------+ | id | name | +----+--------+ | 1 | tomita | | 2 | suzuki | +----+--------+ 2 rows in set (0.00 sec) |