一:配置数据库
1.打开cmd命令行,输入:mysql -uroot -p
,输入密码进入mysql
![image-20200716203109242](https://gitee.com/xuexianqi/img/raw/master/img/20200716203110.png)
2.创建数据库:luffyapi
create database luffyapi;
![image-20200716203145746](https://gitee.com/xuexianqi/img/raw/master/img/20200716203146.png)
3.创建数据库用户,并且授予luffyapi
这个库的权限
grant all privileges on luffyapi.* to 'luffyapi'@'%' identified by 'Luffy123?';
grant all privileges on luffyapi.* to 'luffyapi'@'localhost' identified by 'Luffy123?';
flush privileges;
![image-20200716204204339](https://gitee.com/xuexianqi/img/raw/master/img/20200716204205.png)
4.可能会出现如下报错
![image-20200716204135193](https://gitee.com/xuexianqi/img/raw/master/img/20200716204136.png)
5.Navicat连接测试
①打开Navicat,连接 - MySQL
![image-20200716204456156](https://gitee.com/xuexianqi/img/raw/master/img/20200716204457.png)
②填写如下信息,点击测试连接,成功后点击“确定”
连接名:自定义,见名知意即可
主机:默认本机是 localhost,远程连接就填IP
端口:默认是3306,无需改动
用户名:第3步创建的用户名
密码:第3步创建的密码
![image-20200716204639188](https://gitee.com/xuexianqi/img/raw/master/img/20200716204640.png)
二:项目连接数据库
1.打开dev.py
,进行如下设置:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 数据库引擎为MySQL
'NAME': 'luffy', # 数据库名
'USER': 'luffy', # 用户名
'PASSWORD': 'Luffy123?', # 密码
'HOST': 'localhost', # 主机,本机默认为localhost
'PORT': 3306 # 端口,默认MySQL端口为3306
}
}
import pymysql # 导入pymysql
pymysql.install_as_MySQLdb() # 用pymysql替代MySQLdb
![image-20200716205149865](https://gitee.com/xuexianqi/img/raw/master/img/20200716205151.png)
2.删除原来的db.sqlite3
![image-20200716205600485](https://gitee.com/xuexianqi/img/raw/master/img/20200716205601.png)
3.运行项目,可能会出现如下报错,需要修改一下源码
![image-20200716211414293](https://gitee.com/xuexianqi/img/raw/master/img/20200716211415.png)
![image-20200716211529444](https://gitee.com/xuexianqi/img/raw/master/img/20200716211530.png)
有时候也有可能会出现这样的错误:
![image-20200716212102400](https://gitee.com/xuexianqi/img/raw/master/img/20200716212103.png)
4.访问,成功
![image-20200716211621612](https://gitee.com/xuexianqi/img/raw/master/img/20200716211623.png)