Django使用MySQL

說明:這是在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__)

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容