Python3 Django連接MySQL

1、指定連接pymysql(python3.x)

配置_init_.py所在地址
  • 先配置init.py
import pymysql

pymysql.install_as_MySQLdb()
#Django連接MySQL時(shí)默認(rèn)使用MySQLdb驅(qū)動(dòng),但MySQLdb不支持Python3,因此這里將MySQL驅(qū)動(dòng)設(shè)置為pymysql


2.配置連接mysql文件信息

  • settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django_demo',    #你的數(shù)據(jù)庫(kù)名稱(chēng) ,這個(gè)庫(kù)需要已經(jīng)存在
        'USER': 'root',   #你的數(shù)據(jù)庫(kù)用戶(hù)名
        'PASSWORD': '123456', #你的數(shù)據(jù)庫(kù)密碼
        'HOST': '10.177.15.139', #你的數(shù)據(jù)庫(kù)主機(jī),留空默認(rèn)為localhost
        'PORT': '3306', #你的數(shù)據(jù)庫(kù)端口
    }
}

3. 在 django_demo\application\models.py里面寫(xiě)建表語(yǔ)句

from django.db import models

# Create your models here.
class UserInfo(models.Model):
    id=models.AutoField(primary_key=True)
    name=models.CharField(max_length=16,help_text=u'名字')
    moblie=models.IntegerField()
    password=models.CharField(max_length=24)

4.在終端執(zhí)行命令

1、生成遷移文件:
python manage.py makemigrations

2、生成數(shù)據(jù)庫(kù)表:
python manage.py migrate

** 注意**:在生成遷移文件時(shí)候可能會(huì)報(bào)錯(cuò):
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.

解決方案:
找到Python環(huán)境下 django包的base.py文件,路徑如下:
python3.6/site-packages/django/db/backends/mysql/base.py

注釋base.py 中如下部分(35/36行)
# 注釋以下兩行代碼;解決 :django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.
# if version < (1, 3, 13):
#     raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)

  • 如果報(bào)錯(cuò):AttributeError: ‘str’ object has no attribute ‘decode’
    找到:site-packages\django\db\backends\mysql\operations.py文件(46行)

將decode改為encode,如下:

        #  執(zhí)行django_demo>python manage.py makemigrations 時(shí)候報(bào)錯(cuò):AttributeError: 'str' object has no attribute 'decode'
        # 解決錯(cuò)誤:
        # if query is not None:
        #     query = query.decode(errors='replace')
        # return query
        if query is not None:
            query = query.encode(errors='replace')
        return query


再執(zhí)行第四步就不會(huì)報(bào)錯(cuò)了

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

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

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