基于虚拟机执行
ipconfig
查看ip信息
mysql -uroot -proot
登录,u为user,p为password
也可mysql -uroot -p
,可隐藏输入密码
\q
退出
也可通过win+r,输入sevices.msc进入服务,找到MySQL结束。
show databases;
可查看mysql服务器管理多少个数据库
use db;
选择数据库
show tables;
可查看当前数据库下有多少表
此处需要注意,要先选择数据库,才能show tables
select database();
可查看当前所处的数据库
select user();
可查看当前用户
select @@datadir;
查看data文件夹路径
select @@basedir;
查看安装路径
create database citest;
创建数据库
? contents;
mysql帮助的用法
如我想查看data types中的 date 的用法:
其中 ? contents;
返回的为主菜单
create table dep(id int not null auto_increament primary key, name varchar(25));
其中create table
为创建表,表名为 dep。
第一列col_name 为id, 类型为int, 要求not null, 且为自增列(auto_increment),同时为主键。
第二列col_name为name, 类型为varchar。
这样就建好了一个表
再建一个复杂亿点的emp表
create table emp(
id int not null auto_increment primary key,
dep_id int,
name varchar(25),
age int default 18,
sex enum('M', 'F') default 'M',
CONSTRAINT fk_emp_01 FOREIGN KEY(dep_id) REFERENCES dep(id)
);
表名为emp
第一列col_name 为 id,int类型,规定not null, 为primary key,是自增列
第二列col_name 为dep_id,int类型
第三列col_name 为 name,varchar类型
第四列col_name 为 age,int类型,默认为18
第五列col_name 为 sex,enum类型(枚举类型,为’M’ 或 ‘F’),默认为’M’
同时有约束条件,foreign key名为fk_emp_01,外键为dep_id,外键列为dep表的id列
desc dep
查看表的结构
show create table dep \G
查看创建表语句
也可理解为mysql帮你写的创建该表的语句
对表结构的操作
DDL
增加:
alter table stu add pro varchar(23) after age;
对stu表增加一列,列名为pro,类型为varchar,在age后一列增加。
此处也可以alter table stu add pro varchar(23) first age;
,即加到age前一列。
若需直接加到最开始(末尾),可
alter table stu add pro varchar(23) first;
alter table stu add pro varchar(23);
修改:
alter table stu modify pro int default 3;
修改表stu的pro列,将其改为int,且默认值为3
关键字modify后接列的重新定义
列重命名:
alter table stu change pro prof varchar(3) default 'art'
将stu表中的pro列,重命名为prof,且类型改为varchar,默认值为’art’。
删除:
alter table stu drop prof;
表重命名:
alter table stu rename to student;
将表stu重命名为student
DML
增加表的内容
insert into student(name, age, sex, birth) values('zhangsan', 18, 'M', now())
给表student增加一行,name为zhangsan,age为18,sex为M,birth图方便设为当前日期
也可以通过set来进行设置。
insert into student set name='lisi',age=20,sex='F',birth='2000-01-01;
还可以插入多列
insert into student values(null, 'wangwu', 21, 'M', '2001-01-02'),
(null, 'lisa', 21, 'F', '2001-10-10');
更新表的内容
update student set name='alin' where id = 4;
需要注意这里如果不给where条件,则表中所有的那么均会改为alin
删除表的内容
delete from student where id = 4;
❗️❗️❗️