目錄
Django 連接 MySQL數據庫及常見報錯解決
MySQL 的安裝以及設置遠程訪問權限,不屬於本筆記的重點,此處不做多余贅述
前提:
MySQL 安裝成功,且已配置遠程訪問權限(如在本地測試的忽略此項)
終端或者數據庫管理工具連接 MySQL ,並新建項目所需數據庫
CREATE DATABASE drf_shop CHARACTER SET utf8;
創建數據庫一定要將字符編碼設置為utf8,很多錯誤就是沒正確設置編碼導致的!
安裝訪問 MySQL 的 Python 模塊
pip install pymysql
Django 相關配置
工程文件夾(settings平級的文件夾)/_init_.py
from pymysql import install_as_MySQLdb
install_as_MySQLdb()
settings.py 中替換默認 DATABASE
相關配置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # django 數據庫后台
'NAME': 'drf_shop', # 連接數據庫的名稱
'USER': 'root', # 用戶名
'PASSWORD': '123456', # 密碼
'HOST': '127.0.0.1', # 主機
'PORT': '3306', # 端口
}
}
至此,就可以像使用SQLite一樣使用MySQL了!
可能會遇到的報錯
首先需要保證前面所有步驟均配置成功
報錯1: django.core.exceptions.ImproperlyConfigured: mysqlclient 1.x.xx or newer is required; you have 0.x.x.
報錯內容:
raise ImproperlyConfigured('mysqlclient 1.x.xx or newer is required; you have %s.' % Database.__version__)
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
,注釋掉以下內容:
# if version < (1, 3, 13):
# raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)
報錯2:AttributeError: 'str' object has no attribute 'decode'
報錯內容:
File "xx\Python37\lib\site-packages\django\db\backends\mysql\operations.py", line 146, in last_executed_query
query = query.decode(errors='replace')
AttributeError: 'str' object has no attribute 'decode'
解決方法:
打開 xx\Python37\lib\site-packages\django\db\backends\mysql\operations.py
把146行的 decode
修改為 encode
即可