DELETE
语法:delete from 表名 [where condition]
delete from grade;
TRUNCATE
用于完全清空表数据,但表结构、索引、约束不变;
语法:
truncate [table] table_name;
事务 transaction
- 原子性(A):执行事务,要么都成功,要么都失败。
- 一致性(C):执行后,保持数据的一致。
- 隔离性(I): 事务之间相互独立,互不影响
- 持久性(D):数据永久存储在数据库中
事务的隔离级别:
- 读取未提交(Read-uncommitted): 处于此模式下可能会出现脏读、幻象读、不可重复读
- 读取提交(Read-committed):处于此模式下可能会出现幻象读、不可重复读
- 重复读取(repeatable-read):处于此模式下可能会出现幻象读
- 串行化(Serialize):不会出现幻象读
- 脏读:
- 幻读:
SET Autocommit
- set autocommit = 0;关闭自动提交模式
- set autocommit = 1;开启自动提交模式
注意:MySQL默认是自动提交,使用事务时应先关闭自动提交
mysql> select @@autocommit;
+--------------+
| @@autocommit |
+--------------+
| 1 |
+--------------+
mysql> set autocommit = 0;
mysql> select @@autocommit;
+--------------+
| @@autocommit |
+--------------+
| 0 |
+--------------+
事务的实现方式:
- Start transaction :开始一个事务,标记事务的起点
- Commit : 提交一个事务给数据库
- Rollback : 将事务回滚,数据回到本事务的初始状态
- Set autocommit = 1; 还原MyAQL数据库的自动提交
查看默认事务提交方式:
mysql> select @@autocommit;
关闭自动提交事务:
mysql> set autocommit = 0;
过程:
- 开始事务:start transaction;
- 执行一系列SQL : mysql> update tbl_name set name =999 where name = 12;
- 假设出现异常事务回滚mysql> rollback;
- 假设一切正常 :mysql> commit;
课堂案例:
mysql> create database shop;
mysql> use shop;
mysql> create table account
-> (
-> id int not null primary key auto_increment,
-> name varchar(32) not null,
-> cash decimal(9,2) not null
-> );
mysql> insert into account(name,cash) values('A',2000.00);
mysql> insert into account(name,cash) values('B',10000.00);
mysql> select * from account;
+----+------+----------+
| id | name | cash |
+----+------+----------+
| 1 | A | 2000.00 |
| 2 | B | 10000.00 |
+----+------+----------+
mysql> update account set cash = cash - 500 where id =1;
mysql> update account set cash = cashh +500 where id =2;\\发生错误
ERROR 1054 (42S22): Unknown column 'cashh' in 'field list'
mysql> select * from account;
+----+------+----------+
| id | name | cash |
+----+------+----------+
| 1 | A | 1500.00 |
| 2 | B | 10000.00 |
+----+------+----------+
mysql> rollback;
mysql> select * from account;
+----+------+----------+
| id | name | cash |
+----+------+----------+
| 1 | A | 2000.00 |
| 2 | B | 10000.00 |
+----+------+----------+