django 连接mysql数据库及常见报错解决

mysql 的安装以及设置远程访问权限,不属于本笔记的重点,此处不做多余赘述

前提:
mysql安装成功,且已配置远程访问权限(如在本地测试的忽略此项)

终端或者数据库管理工具连接 MySql ,并新建项目所需数据库

  1. CREATE DATABASE drf_shop CHARACTER SET utf8;

创建数据库一定要将字符编码设置为utf8,很多错误就是没正确设置编码导致的!

安装访问 MySQL 的 Python 模块

  1. pip install pymysql

Django 相关配置

工程文件夹(settings平级的文件夹)/init.py
**

  1. from pymysql import install_as_MySQLdb
  2. install_as_MySQLdb()

settings.py 中替换默认 DATABASE 相关配置
**

  1. DATABASES = {
  2. 'default': {
  3. 'ENGINE': 'django.db.backends.mysql', # django 数据库后台
  4. 'NAME': 'drf_shop', # 连接数据库的名称
  5. 'USER': 'root', # 用户名
  6. 'PASSWORD': '123456', # 密码
  7. 'HOST': '127.0.0.1', # 主机
  8. 'PORT': '3306', # 端口
  9. }
  10. }

至此,就可以像使用SQLite一样使用MySQL了!

可能会遇到的报错

首先需要保证前面所有步骤均配置成功

报错1: django.core.exceptions.ImproperlyConfigured: mysqlclient 1.x.xx or newer is required; you have 0.x.x.

报错内容:
**

  1. raise ImproperlyConfigured('mysqlclient 1.x.xx or newer is required; you have %s.' % Database.__version__)
  2. django.core.exceptions.ImproperlyConfigured: mysqlclient 1.x.xx or newer is required; you have 0.x.x.

这里 xx 表示版本,报错版本可能不同但解决方法时一样的
解决方法:
/Python37(python安装目录)/Lib/site-packages/django/db/backends/mysql/base.py,注释掉以下内容:

  1. # if version < (1, 3, 13):
  2. # raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)

报错2:AttributeError: ‘str’ object has no attribute ‘decode’

报错内容:
**

  1. File "xx\Python37\lib\site-packages\django\db\backends\mysql\operations.py", line 146, in last_executed_query
  2. query = query.decode(errors='replace')
  3. AttributeError: 'str' object has no attribute 'decode'

解决方法:
打开 xx\Python37\lib\site-packages\django\db\backends\mysql\operations.py 把146行的decode修改为encode即可