查询当前数据库支持的存储引擎
#储存引擎,基于数据表
show engines;
查询结果:
可以看到,MySQL数据库默认的存储引擎是InnoDB,InnoDB支持事务,行级锁(适合高并发)和外键。
事务
# 创建数据库demo_02
create database demo_02 default charset =utf8mb4;
use demo_02;
# 创建goods_innodb表
create table goods_innodb
(
id int auto_increment,
name varchar(20) not null,
constraint goods_innodb_pk
primary key (id)
)engine=innodb default charset=utf8;
#插入一条数据
insert into goods_innodb(id,name) values (null,'Meta20');
#查询数据
select * from goods_innodb;
查询结果
# 开启事务
start transaction ; # MySQL默认事务级别为:可重复读
# 插入一条新数据
insert into goods_innodb(id,name) values (null,'xiaomi6');
# 未提交
# commit
由于事务未提交,此时在客户端查询不到该数据,注意,此时在本地可以查询到插入数据。
客户端查询结果:
# 提交事务
commit;
客户端查询结果
外键约束
# 创建country表
create table country_innodb
(
country_id int auto_increment,
country_name varchar(50) not null,
primary key (country_id)
)engine=innodb default charset=utf8;
# 插入数据
insert into country_innodb(country_id,country_name) values (null,'China');
insert into country_innodb(country_id,country_name) values (null,'UK');
# 创建city表
create table city_innodb
(
city_id int auto_increment,
city_name varchar(50) not null,
country_id int not null,
constraint city_innodb_pk
primary key (city_id),
constraint city_innodb_country_innodb_country_id_fk
foreign key (country_id) references country_innodb (country_id)
on update cascade
)engine=innodb default charset=utf8;
#插入数据
insert into city_innodb(city_id,city_name,country_id) values (null,'北京',1);
insert into city_innodb(city_id,city_name,country_id) values (null,'广州',1);
insert into city_innodb(city_id,city_name,country_id) values (null,'纽约',2);
其中,对于city_innodb表:
Update rule:cascade,更新主表时,如果子表存在关联记录,更新子表关联记录;
Delete rule:restrict,删除主表数据时,如果子表存在关联记录,则主表数据不删除。
country_innodb查询结果
city_innodb查询结果
# 删除主表id = 2的记录
delete from country_innodb where country_id=2;
# 删除失败,报错信息:
#[23000][1451] Cannot delete or update a parent row: a foreign key constraint fails (`demo_02`.`city_innodb`, CONSTRAINT `city_innodb_country_innodb_country_id_fk` FOREIGN KEY
# (`country_id`) REFERENCES `country_innodb` (`country_id`) ON UPDATE CASCADE)
# 更新主表,同时更新子表的关联记录
update country_innodb set country_id = 10 where country_id = 1;
更新结果: