全部笔记All notes

综合案例2-记录的插入、更新和删除

阅读 3m 52s3m 52s read

综合案例2-DML操作

本部分内容重点介绍了数据表中数据的插入、更新和删除操作。MySQL中可以灵活的对数据进行插入与更新,MySQL中对数据的操作没有任何提示,因此在更新和删除数据时,一定要谨慎小心,查询条件一定要准确,避免造成数据的丢失。此综合案例包含了对数据表中数据的基本操作,包括记录的插入、更新和删除。

1、案例目的

创建表books,对数据表进行插入、更新和删除操作,掌握表数据的基本操作。books表结构以及表中的记录,如表1和表2所示

表1 books表结构

字段名数据类型主键外键非空唯一自增字段说明
b_idint(11)是否是是否书编号
b_namevarchar(50)否否是否否书名
authorsvarchar(100)否否是否否作者
pricefloat否否是否否价格
pubdateyear否否是是否出版日期
notevarchar(100)否否否否否说明
numint(11)否否是否否库存量

表2 books表中的记录

b_idb_nameauthorspricepubdatenotenum
1Tale of AAADickes231995novel11
2EmmaTJane lura351993joke22
3Story of JaneJane Tim402001novel0
4Lovey DayGeorge Byron202005novel30
5Old LandHonore Blade302010law0
6The BattleUpton Sara301999medicine40
7Rose HoodRichard Haggard282008cartoon28

2、案例操作过程

(1)登录MySQL数据库。

mysql -h localhost -u root -p

截图:

img

(2)创建数据库M_BOOK并选择使用此数据库。

create database M_BOOK;
desc M_BOOK;

截图:

image-20220315141208398

(3)按照表1创建表books,创建成功后用desc查看表结构。

create table books(
	b_id int(11) not null unique,
	b_name varchar(50) not null,
	authors varchar(100) not null,
    price float not null,
    pubdate year not null unique,
    note varchar(100) null,
    num int(11) not null,
    primary key(b_id)
);

截图:

image-20220315142332615

(4)使用select语句查询表中的数据(此处查询结果应为空)

select * from books;

截图:

image-20220315142310880

(5)将表2中的记录插入到books表中,分别使用不同的方法插入记录。

①指定所有字段名插入第1行记录,插入后用select语句查询插入结果

insert into books (b_id,b_name,authors,price,pubdate,note,num) values(1,'Tale of AAA','DIckes',23,1995,'novel',11);
select * from books;

截图:

image-20220315142912049

②不指定字段名插入第2行记录,插入后用select语句查询插入结果

insert into books values(2,'EmmaT','Jane lura',35,1993,'joke',22);
select * from books;

截图:

image-20220315143315288

③同时插入第3~7行记录,插入后用select语句查询插入结果

insert into books (b_id,b_name,authors,price,pubdate,note,num)
values (3,'Story of Jane','Jane Tim',40,2001,'novel',0),
(4,'Lovey Day','George Byron',20,2005,'novel',30),
(5,'Old Land','Honore Blade',30,2010,'law',0),
(6,'The Battle','Upton Sara',30,1999,'medicine',40),
(7,'Rose Hood','Richard Haggard',28,2008,'cartoon',28);

截图:

image-20220315144009242

(6)使用select语句查询小说类型(novel)的书的所有信息。

select * from books where note='novel';

截图:

image-20220315144355595

(7)将小说类型(novel)的书的价格都增加5,并在更新后使用select语句查询小说类型(novel)的书的所有信息

update books set  price=price+5 where note='novel';
select * from books where note='novel';

截图:

image-20220315145957535

(8)使用select语句查看书名为EmmaT的信息

select * from books where b_name='EmmaT';

截图:

image-20220315150138907

(9)将名为EmmaT的书价格改为40,并使用select语句查询更新后的该书信息。

update books set  price=40 where b_name='EmmaT';
select * from books where b_name='EmmaT';

截图:

image-20220315150252053

(10)查询库存量为0的书的所有信息。

select * from books where num=0;

截图:

image-20220315150322666

(11)删除库存量为0的书的所有信息,并使用select语句查询库存量为0的书的所有信息(此处应为空)。

delete from books where num=0;
select * from books where num=0;

截图:

image-20220315150431488

相关文章

核心教程