說明:這是在python3.6.8+Django2.2的環(huán)境下的MySQL的使用
首先是去MySQL客戶端去創(chuàng)建數(shù)據(jù)庫,默認數(shù)據(jù)集設置為utf8
CREATE DATABASE IF NOT EXISTS?dbname?DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
然后安裝 mysqlclient 模塊,通過?mysqlclient?模塊完成和數(shù)據(jù)庫之間的連接。
pip install?mysqlclient
最后更改Django數(shù)據(jù)庫配置
DATABASES = {
'default': {
'ENGINE':'django.db.backends.mysql',
? ? ? ? 'NAME':'chatroom',
? ? ? ?'HOST':'127.0.0.1',
? ? ? ? 'USER':'root',
? ? ? ? 'PASSWORD':'password',
? ? ? ? 'PORT':'3306',? ? }}
注意:安裝pymysql模塊,通過pymysql模塊完成和數(shù)據(jù)庫之間的連接,會出現(xiàn)以下兩種錯誤
錯誤一:No module named 'MySQLdb'
原因:python3連接MySQL不能再使用mysqldb,取而代之的是pymysql。
解決方法:在python的MySQL包中,即路徑:C:\Users\adong\AppData\Local\Programs\Python\Python36\Lib\site-packages\Django-2.0.3-py3.6.egg\django\db\backends\mysql
下的__init__.py文件中加入:
import pymysql
pymysql.install_as_MySQLdb()
錯誤二:django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.3 or newer is required; you have 0.7.11.None
原因:在解決了錯誤一以后出現(xiàn)了此錯誤。
解決方法:在python的MySQL包中,即路徑:C:\Users\adong\AppData\Local\Programs\Python\Python36\Lib\site-packages\Django-2.0.3-py3.6.egg\django\db\backends\mysql
下的 base.py 文件中,注釋掉一下兩行代碼:
if version < (1, 3, 3):
? ? raise ImproperlyConfigured("mysqlclient 1.3.3 or newer is required; you have %s" % Database.__version__)