对数据库的操作
显示系统中所有数据库
1 | show databases ; |
创建数据库
语法:create database 表名 default character set = “字符集”;
指令
1
create database test default character set = "utf8";
进入数据库
语法:use 库名
说明:如果要操作一个库里的表,首先要进入到这个数据库中。
指令
1
use test;
删除数据库
语法:drop database 库名
说明:谨慎操作
指令
1
drop database test;
对数据表的操作
显示库中所有的表
语法:show tables;
指令
1
2use mysql; // 打开库
show tables; // 查看所有表
创建单个主键的数据表
语法:create table 表名 (字段1 类型 是否可以为空 是否是主键,字段2……);
指令
1
2
3
4
5
6create table student
(
id int(10) auto_increment not null primary key,
name char(10) null,
gender char(2) null
);说明:
- int、char 表示字段的数据类型,括号内的数字表示长度。
- auto_increment 表示字段值自增。
- not null 和 null 表示该字段是否可以为空.
- primary key 表示将该字段设为主键。
创建多个主键的数据表
语法:create table 表名 (字段1 类型 是否可以为空 是否是主键,字段2……,PRIMARY KEY (主键1字段,主键2字段));
指令
1
2
3
4
5
6
7create table sc
(
sno char(10) not null,
cno char(5) not null,
degree decimal(4,1) null,
PRIMARY KEY (sno,cno)
);
查看表结构
语法:desc 表名;
指令
1
desc student;
查看表中所有数据
语法:select * from 表名;
指令
1
select * from student;
在表中写入数据
语法:insert into 表名(字段1,字段2……) values (字段1的值,字段2的值……)
指令
1
2
3
4insert into student(name, gender) values
('张三','男'),
('李四','女'),
('王五','男');
复制表结构
语法:create table 新表名 like 旧表名
指令
1
create table stu like student;
复制表中所有数据
语法:create table 新表名 as (select * from 旧表名)
指令
1
create table stu as (select * from student);
修改表结构
语法:alter table 表名 modify 字段名 字段其他信息
指令
1
2alter table student
modify gender char(10);
删除一个字段
语法:alter table 表名 drop column 字段名;
指令
1
2alter table sc
drop column degree;
删除一条记录
语法:delete from 表名 where 条件;
指令
1
delete from student where id=3;
删除数据表
语法:drop table 表名
指令
1
drop table sc;