SQL事务的用法示例

开启事务的三种方式:

1.在此线程内有效,上一事务结束后,立刻自动开启新的事物

mysql> set autocommit = 0;

2.临时开启

mysql> begin;

3.临时开启

mysql> start transaction;

提交事务:

mysql> commit;

回滚事务:

mysql> rollback;

插入保存点:

mysql> savepoint a;

插入后,再回滚到a时,意味着a之后的语句全部失效 

mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> insert into jdbc_test values(null,"li","jkhsdfjdgh");
Query OK, 1 row affected (0.02 sec)

mysql> savepoint a;
Query OK, 0 rows affected (0.02 sec)

mysql> insert into jdbc_test values(null,"wang","45456456");
Query OK, 1 row affected (0.00 sec)

mysql> savepoint b;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from jdbc_test;
+---------+-----------+---------------------+
| jdbc_id | jdbc_name | jdbc_desc           |
+---------+-----------+---------------------+
|       1 | kobe      | twotimesmvp         |
|       2 | levin     | arookie             |
|       3 | jodan     | mvp of the history  |
|       4 | kobe      | two times mvp       |
|       5 | levin     | a rookie            |
|       6 | jodan     | mvp of the history  |
|       7 | mcgrady   | two times defenwang |
|       8 | shaq      | rebound             |
|      10 | lebron    | mvp                 |
|      11 | bird      | mop                 |
|      12 | li        | jkhsdfjdgh          |
|      13 | wang      | 45456456            |
+---------+-----------+---------------------+
12 rows in set (0.00 sec)

mysql> rollback to a;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from jdbc_test;
+---------+-----------+---------------------+
| jdbc_id | jdbc_name | jdbc_desc           |
+---------+-----------+---------------------+
|       1 | kobe      | twotimesmvp         |
|       2 | levin     | arookie             |
|       3 | jodan     | mvp of the history  |
|       4 | kobe      | two times mvp       |
|       5 | levin     | a rookie            |
|       6 | jodan     | mvp of the history  |
|       7 | mcgrady   | two times defenwang |
|       8 | shaq      | rebound             |
|      10 | lebron    | mvp                 |
|      11 | bird      | mop                 |
|      12 | li        | jkhsdfjdgh          |
+---------+-----------+---------------------+
11 rows in set (0.00 sec)

 

你可能感兴趣的:(SQL)