数据库的操作
1.数据库创建
create database if not exists 表名 default charset=utf8
create database if not exists student default charset=utf8;
2.查看所有库
show databases;
3.进入库
use 库名
use student;
4.删除库
drop database 库名
drop database student;
数据表的操作
1.创建表
create table 表名(字段名,类型,【字段约束】…)
create table users(
-- 创建ID字段,为正整数,不允许为空 主键,自动递增
id int unsigned not null primary key auto_increment,
-- 创建 存储 名字的字段,为字符串类型,最大长度 5个字符,不允许为空
username varchar(5) not null,
-- 创建存储 密码 的字段,固定长度 32位字符, 不允许为空
password char(32) not null,
-- 创建 年龄 字段,不允许为空,默认值为 20
age tinyint not null default 20 )engine=innodb default charset=utf8;
2.查看表结构
desc 表名
desc users;
3.查看建表语句
show create table 表名;
show create table users;
4.修改表结构
alter table 表名 操作
操作1:添加字段
--在 users 表中 追加 一个 num 字段
alter table users add num int not null;
-- 在指定字段后面追加字段,在 users 表中 age字段后面 添加一个 phone
alter table users add phone char(11) not null after age;
-- 在表的最前面添加一个字段
alter table users add aa int first;
操作2:删除字段
删除字段 alter table 表名 drop 被删除的字段名
alter table users drop aa;
操作3:修改字段
change: 可以修改字段名,
modify: 不能修改字段名。
# 修改表中的 num 字段 类型,使用 modify 不修改表名
alter table users modify num tinyint not null default 12;
# 修改表中的 num 字段 为 int并且字段名为 nn
alter table users change num mm int;
5.修改表名
语法:alter table rename as 新表名
6.更改表中的自增的值
# 在常规情况下,auto_increment 默认从1开始继续递增
alter table users auto_increment = 1000;
7.删除表
drop table 表名
表中数据的操作
1.添加数据
格式: insert into 表名[(字段列表)] values(值列表…);
--标准添加(指定所有字段,给定所有的值)
insert into stu(id,name,age,sex,classid) values(1,'zhangsan',20,'m','lamp138');
--指定部分字段添加值
insert into stu(name,classid) value('lisi','lamp138');
-- 不指定字段添加值
insert into stu value(null,'wangwu',21,'w','lamp138');
-- 批量添加值
insert into stu values
-> (null,'zhaoliu',25,'w','lamp94'),
-> (null,'uu01',26,'m','lamp94'),
-> (null,'uu02',28,'w','lamp92'),
-> (null,'qq02',24,'m','lamp92'),
-> (null,'uu03',32,'m','lamp138'),
-> (null,'qq03',23,'w','lamp94'),
-> (null,'aa',19,'m','lamp138')
2.修改数据
格式:update 表名 set 字段1=值1,字段2=值2,字段n=值n… where 条件
-- 将id为11的age改为35,sex改为m值
update stu set age=35,sex='m' where id=11;
-- 将id值为12和14的数据值sex改为m,classid改为lamp92
update stu set sex='m',classid='lamp92' where id=12 or id=14
--等价于下面
update stu set sex='m',classid='lamp92' where id in(12,14);
3.删除数据
格式:delete from 表名 [where 条件]
-- 删除stu表中id值为100的数据
delete from stu where id=100;
-- 删除stu表中id值为20到30的数据
delete from stu where id>=20 and id<=30;