1.显示所有库:
show databases;
2.创建库:
create database 库名;
重复创建会报错,修正如下
create database if not exists 库名;
3.删除库
drop database 库名;
重复删除会报错,如果不知道数据库是否存在
drop database if exists 库名;
4.进入数据库
use 库名;
2.表级操作
1.显示所有的表:
show tables; # 查看当前数据库中的数据表。
show tables from mysql; # 查看`mysql`这个数据库中的数据表。
2.创建表:
create table student (name varchar(20),age int,sex char(20);
数据库和python不同,回车和空格要求没有那么严格,所以,当你创建多个字段时,可以回车每行输入一个字段。
重复创建会报错,修正如下
create table if not exists student (name varchar(20),age int, sex char(20);
3.显示创建表的信息
show create table student;
4.查看数据表结构
show columns from 表名;
describe 表名;
可简写为:
desc 表名;
5.删除表:
drop table student;
6.修改表结构
增加 :ADD 添加字段
删除 :DROP 删除字段
修改 :MODIFY #改列的数据类型
CHANGE #改列名和数据类型
RENAME #改表名
>修改表名:
alter table new_table rename to old_table;
>修改字段名:
alter table old_table change id stu_id int;
>修改字段类型:
alter table old_table modify stu_id tinyint;
>添加字段:
alter table old_table add age tinyint; # 添加单列
alter table old_table add (aa int, bb int, cc int); # 添加多列
>删除字段:
alter table old_table drop age;
alter table old_table drop aa,drop bb, drop cc;
3.表数据的增删改查
1.增
插入字段
a.全字段插入:有几个字段就必须输入几个字段,否则报错
insert into student values("飞飞",18);
b.指定字段插入
insert into student(name) values("哈哈");
c.多行插入
insert into student values("你好",5),("我好", 6);
2.查
a.全字段查询
select * from student;
b.指定字段查询
select name from student;
select name,age from student;
c.带条件的查询
select name,age from student where age = 18;
select name,age from student where name = "飞飞";
3.改
a.修改所有数据:
update student set age=24;
b.修改满足条件的数据:
update student set age=24 where name = "飞";
c.修改多个:
update student set age=24,name="嘻嘻" where name="哈哈";
update student set age=24,name="嘻嘻";
# 注意:一定要写where条件,不然会修改表中全部数据
4.删
a.条件删除
delete from student where name="嘻嘻";
b.删除全部数据
delete from student;
# 注意:一定要写where条件,不然会删除表中全部数据
# 删除都是操作一行,如果只是想要修改某个字段值,可以使用update
update student set age=NULL where name = "飞";