首页 > 技术文章 > Django(五):连接MySQL

xiaoqichaoren 2020-02-26 14:00 原文

1.更改数据源

首先在settings中配置mysqlenginenameuserpasswordhost(主机号),port(端口号)
 
2.向mysql中添加表
由于之前是在sqlite3中建的表,数据存放在sqlite3数据库中。
把数据转移到mysql当中,需要做一下数据的迁移:python manage.py migrate
*如果数据库当中没有nameHelloDjango(上一步更改的目标数据库)的数据库,还需要使用命令行 create database HelloDJango charset utf8; 创建一个数据库
Database V MySQC= schemas 1 collations 222
 
这时我们发现,迁移失败了,原因是缺少mysql连接用的驱动
(venv) C:\Users\YY\Desktop\DjangoProject\He110Django>python manage. py migrate Traceback (most recent call last): File "C: import MySQLdb as Database Bbdu1eNotFoundError: No nu)dule named ' MySOLdb' The above exception was the direct cause of the f0110L•Jing exception : Traceback (most recent call last):
 
 
3.连接mysql驱动
常见的驱动有:
mysqlclient:python2python3都能直接使用,缺点是对MySQL的安装有要求,必须在指定位置存在配置文件
python-mysql:只对python2支持,不支持python3
pymysql:对于23都支持,最大的优点是它可以伪装成前面两个
 
 
选择pymysql作为连接驱动,执行安装命令:pip insall pymysql
安装后,在项目的目录下,将连接伪装成mysqldb,写在__init__.py文件中
import pymysql
pymysql.install_as_MySQLdb()
 
V HelloDjango & APP Django*iB.md V HelloDjango asgi.py settings.py urls.py wsgi.py subAPP V templates index.html import pymysql pymysql . ) 4
 
驱动连接好后,在执行python manage.py migrate
会出现如下报错
 
File "D: \Program init .pv", line 127, in import_module return _ bootstrap. : ] , package, level) File "C: . ply'", 1 raise ImproperlyConfigured( 'mysqlclient 1.3.13 or newer is required; you have %s.' % Database. ve rs10n django. core. exceptions . ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.
原因是需要更高版本的mysqlclient,因为我们用pymysql伪装的,不能更新
 
解决方法有三个:
一:降低django版本,由于高版本的django默认使用mysqlclient 1.3.13以上版本,降低到2.1.4版本即可
二(仍使用django 2.2版本):将bsae.py中的验证版本的部分注掉,具体在
https://blog.csdn.net/weixin_33127753/article/details/89100552 ,但是没有从根源上解决
三:改用mysqlclient1.3.13以上的驱动
3.11补第四个方法(不需要更改django版本也不需要修改任何代码的方法):
1.在项目的配置文件夹下的__init__.py中,pymysql.install_as_MySQLdb()(把pymysql伪装成mysqldb)之前。重写属性version_info(设置版本号):pymysql.version_info = (1, 3, 13, "final", 0)
2.pymysql.install_as_MySQLdb()前,重写类方法last_executed_query(),将query = query.decode(errors='replace')改写为query = query.encode(errors='replace')DatabaseOperations.last_executed_query = my_last_executed_query
*注:用于替代的新函数my_last_executed_query如下图)
3.最后一步伪装pymysqlpymysql.install_as_MySQLdb()
iews.py ' _ init_.py« models.py• urls.pyx students.html llJimport pymysql from django.db.backends.mysql . operations import Databaseoperations L 'def cursor, sql, params) : query = getattr(cursor, executed", None) if query is not None: query = query . replace • ) # decode->encod return query 2 # overwrite Databaseoperations. last_executed query = query # set version=1.3.13 pymysql.version_info = (1, 3, 13, "final", O) pymysql. ( ) 1
 

 

推荐阅读