1.数据库的创建、修改、删除
1.在MySQL中创建一个名为db_school的数据库,要求设置默认字符集为GB2312,字符集的校对规则为gb2312_chinese_ci。
create database db_school default character set GB2312 collate gb2312_chinese_ci;
2.查看当前用户可查看的数据库列表。
show databases;
3.修改已有数据库db_school的默认字符集和校对规则分别为GBK, GBK_chinese_ci。
alter database db_school default character set GBK collate GBK_chinese_ci;
4.删除数据库db_school,并使用show databases查看。
drop database db_school;
2.数据表的创建、修改、删除
5.首先按照第1题的要求重新创建db_school,然后在数据库db_school中定义学生表tb_student,其表结构如表1所示,并要求使用InnoDB引擎存储表数据。
use db_school;
create table if not exists tb_student(
studentNo char(10) not null comment"学号",
studentName varchar(10) not null comment"姓名",
sex char(2) comment"性别",
birthday date comment"出生日期",
native varchar(20) comment"籍贯",
nation varchar(10) default"汉" comment"民族",
classNo char(6) comment"所属班级",
primary key(studentNo)
)ENGINE=INNODB;
6.用命令show tables查看当前数据库中的所有表。
show tables;
7.用命令desc tb_student或者show columns from tb_student命令查看tb_student的表结构。
desc tb_student;
show (full) columns from tb_student;
8.用命令show create table tb_student查看tb_student表的详细表结构。
show create table tb_student;
9.将tb_student的表结构复制到tb_student2,并向tb_student2中添加一个INT型字段id,要求其不能为NULL,取值唯一且自动增加,并将该字段添加到表的第一个字段。
复制表结构:create table if not exists tb_student2 like tb_student;
复制表结构和数据:create table if not exists tb_student2 select * from tb_student;
alter table tb_student2 add id int unique auto_increment not null first;
10.向tb_student表中添加一个varchar(16)类型的字段department,用于描述学生所在院系,要求设置其默认值为“城市学院”,并将该字段添加到原表nation之后。
alter table tb_student add department varchar(16) default"城市学院" comment"院系" after nation;
11.将tb_student中的字段birthday重命名为age,并将其数据类型更改为TINYINT,允许其为NULL,默认值为18。用DESC 查看tb_student。
alter table tb_student change birthday age tinyint default"18";
12.将tb_student表中的字段department的默认值删除。
alter table tb_student modify department varchar(16) comment"院系";
13.将tb_student表中的字段department的默认值改为’环化学院’。
alter table tb_student modify department varchar(16) default"环化学院" comment"院系";
14.将tb_student表中的字段department的数据类型更改为varchar(20),取值不允许为空,并将此字段移至字段studentName之后。用desc tb_student命令查看结果。
alter table tb_student modify department varchar(20) not null default"环化学院" comment"院系" after studentName;
15.删除数据表tb_student2中的字段id。
alter table tb_student2 drop id;
16.使用RENAME [TO]子句将数据库db_school中的数据表tb_student2重新命名为backup_tb_student。
rename table tb_student2 to backup_tb_student;
17.使用RENAME TABLE语句将数据库db_school中的表backup_tb_student再重新命名为tb_student2。
alter table backup_tb_student rename to tb_student2;
18.删除数据库db_school中的数据表tb_student,tb_student2。
drop table if exists tb_student,tb_student2;