python用django连接mysql_Python3 Django连接MySQL

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

02ffb2eb53d7

配置_init_.py所在地址

先配置init.py

import pymysql

pymysql.install_as_MySQLdb()

#Django连接MySQL时默认使用MySQLdb驱动,但MySQLdb不支持Python3,因此这里将MySQL驱动设置为pymysql

2.配置连接mysql文件信息

settings.py

DATABASES = {

'default': {

'ENGINE': 'django.db.backends.mysql',

'NAME': 'django_demo', #你的数据库名称 ,这个库需要已经存在

'USER': 'root', #你的数据库用户名

'PASSWORD': '123456', #你的数据库密码

'HOST': '10.177.15.139', #你的数据库主机,留空默认为localhost

'PORT': '3306', #你的数据库端口

}

}

3. 在 django_demo\application\models.py里面写建表语句

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.在终端执行命令

1、生成迁移文件:

python manage.py makemigrations

2、生成数据库表:

python manage.py migrate

** 注意**:在生成迁移文件时候可能会报错:

django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.

解决方案:

找到Python环境下 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__)

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

找到:site-packages\django\db\backends\mysql\operations.py文件(46行)

将decode改为encode,如下:

# 执行django_demo>python manage.py makemigrations 时候报错:AttributeError: 'str' object has no attribute 'decode'

# 解决错误:

# if query is not None:

# query = query.decode(errors='replace')

# return query

if query is not None:

query = query.encode(errors='replace')

return query

再执行第四步就不会报错了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值