一.安装MySQL
1.常用MySQL5.7,首先安装MySQL,
(一)

(二)

(三)

(四)

(五)

2.配置环境变量
打开MySQL安装路径,在其中找到bin文件,复制路径,打开系统高级设置,点击环境变量,在下方找到path,将bin文件路径粘贴其中。
3.检验安装是否完成
win + r 输入cmd,打开命令提示符,输入指令:net start | find "MySQL",这将显示正在运行的服务中是否包含 MySQL。如果 MySQL 服务正在运行,你会看到类似 MySQL 的输出。
4.连接mysql
指令:mysql -u root -p,回车后会提示输入root密码,如果连接成功,你将进入 MySQL 的命令行界面。

二.MySQL常用指令
1.数据库
create database 数据库名 charset=utf8; 创建数据库
show databases; 显示所有数据库

use 数据库名; 使用数据库名

drop database 数据名; 删除数据库
2.数据表
show tables; 显示数据库中所有表

create table 表名 (列名 类型 约束1 约束2,列名 类型 约束1 约束2,...); 创建表

desc 表名; 查看表结构


删除列名

添加列名

修改列名

3.约束
主键: primary key
非空:not null
自增长:auto_increment
唯一:unique
默认值:default
外键:foreign key
检查:check (mysql8才能用)
4.增删改查
(1)查
select * from 表名; 适用于表中数据相对较少时
select 列名,列名 from 表名;
select 列名 as 别名,列名 as 别名 from 表名;
1.1.where 条件
比较运算符 = >= > <= < != <>
逻辑运算符 and or not
判空 is null, is not null
精确比较 in in [a, b, c]
范围比较 between and between 5 and 10
像 like % 代表多个字符 _ 一个字符
1.2.关联查询
嵌套查询
第一次查询的结果作为第二次查询的条件
表连接
笛卡尔连接
一个表中每一行都和另外一个表中所有行连接
内连接
inner join
例子:select user.id as 用户id, user.username as 用户名, role.nick as 昵称, role.level as 等级 from user inner join role on user.id = role.user_id;
外连接
左外连接 left join 以左表为主,左表条件满足 正常显示 不满足 右侧补null
例子:select * from user left join role on user.id = role.user_id;
右外连接 right join 以右表为主,右表条件满足 正常显示 不满足 左侧补null
例子:select * from role right join user on user.id = role.user_id;
全连接
left join union right join
例子: select * from user right join role on user.id = role.user_id union select * from user left join role on user.id = role.user_id;
1.3.去重,分组,排序,分页
去重
distinct 单独列展示 并对列去重
例子: select distinct user_id from role;
分组
group by
一般结合count(*)进行统计
例子: select info as '组信息', count(*) as 个数 from role group by info;
排序
列排序
order by asc 升序 desc 降序
例子:select * from role order by user_id desc , id asc ;
分页
limit
一个数字n代表前n个 limit n
两个数字m n limit m , n
例子:select * from role limit 5; select * from role limit 2,2;
(2)增
insert into 表名 values (值1,值2,值3), (值1,值2,值3); 值的个数与列的个数一致
insert into 表名 (列1,列2,列3) values (值1,值2,值3); 可以指定 哪些列的数据,没有默认值的列必须插入
insert into 表名 set 列1=值1,列2=值2; 插入1行指明插入的列与其值
(3)改
update 表名 set 列1 = 值1 where 条件;
如果没有 where 条件 就修改整个表。
(4)删
delete from 表名 where 条件;
如果没有 where 条件 就清空表
5.用户
创建用户
create user '用户名'@'%' identified by '123456';
分配权限
grant 权限列举 on 数据库名.表名 to '用户名'@'%'; all 所有权限 *.* 所有数据库中的所有表
删除用户
drop user '用户名'@'%';
修改密码
alter user '用户名'@'%' identified by '123456';
6.外键
关系型数据库表与表之间存在关联关系
外键:一个表中的某一列是另外一个表中的主键
创建,添加
constraint 外键名 foreign key (列名) references 表 (列)on update cascade on
delete cascade;
删除
alter table 表名 drop foreign key 外键名;
7.函数
查看当前数据库
select database();
查看当前用户
select user();
查看版本
select version();
现在时间
select now();
当前日期
select curdate();
当前时间
select curtime();
时间戳
select unix_timestamp();
三.mysql与pycharm
首先安装对应的包,打开终端,输入:pip install pymysql
第一步:导入模块
第二步:构建连接实例

user指的是用户名,
password指的是用户密码,
select_db 指的是数据库名。
第三步:构建游标

第四步 :关闭游标,关闭连接

这样数据库就与mysql连接上了。