VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > python入门教程 >
  • [Django] 数据库驱动

参考链接:

  1. Django 连接MySQL的驱动设置

    对于在Django 中连接MySQL 的驱动,有以下三种:

    1. mysqlclient
    2. mysql-connector-pythom
    3. pymysql (建议:这个包已经有一年未升级了,本人不建议使用)。
  2. python3应该用pymysql还是mysqlclient?两者有什么区别?

    There are currently a few options for using Python 3 with mysql:

    • mysql-connector-python
      Officially supported by Oracle
      Pure python
      A little slow
      Not compatible with MySQLdb
    • pymysql
      Pure python
      Faster than mysql-connector
      Almost completely compatible with MySQLdb, after calling pymysql.install_as_MySQLdb()
    • cymysql
      fork of pymysql with optional C speedups
    • mysqlclient
      Django's recommended library
      Friendly fork of the original MySQLdb, hopes to merge back some day
      The fastest implementation, as it is C based
      most compatible with MySQLdb, as it is a forkDebian and Ubuntu use it to provide both python-mysqldb andpython3-mysqldb packages.

环境介绍

Django3.2 + mysql5.7.35

mysqlclient

安装的时候需要安装前置库或mysql,生产环境部署困难,弃之

For Red Hat
sudo yum install python3-devel mysql-devel
pip install mysqlclient
For Debian
sudo apt-get install python3-dev default-libmysqlclient-dev build-essential
pip install mysqlclient

pymysql

(大概50%的概率)报错ModuleNotFoundError at XXXXX,提示:No module named 'MySQLdb.connections'
网上的教程说是在__init__.pysettings.pymanage.py里写入:

import pymysql
pymysql.install_as_MySQLdb()

但是不论在哪里写都有这样的报错(发生位置不一样),弃之

mysql-connector-python

官方文档

  1. settings.py里更新DATABASE的设置:
    DATABASES = {
        'default': {
            'ENGINE': 'mysql.connector.django', # 旧为'django.db.backends.mysql'
            'NAME': 'controller',
            'USER': 'root',
            'PASSWORD': 'nbc@mux_dev',
            'OPTIONS': {                        # 新增字段'OPTIONS'
                'autocommit': True,             # 官网里有的字段,不知道啥用
                'use_pure': True,               # 报错TypeError,搜了下,加上这个就好使了
            },
            'HOST': '10.12.198.243',
            'PORT': '3316'
        }
    }
    
  2. pip安装mysql-connector-python,卸载另外俩,目前能稳定运行

报错记录:TypeError: sequence item 1: expected a bytes-like object, str found
搜索得到:Django: how to install mysql/connector python with pip3
某个回答的某条评论:

@Lucio please, update your answer: mysql-connector-python >= 8.0.13 has a bug, making it impossible to work with Django: code.djangoproject.com/ticket/30469 As a workaround, add 'use_pure': True to the 'OPTIONS'.– Dmytro GiermanOct 31 '19 at 7:58

添加'use_pure': True后不报错了


作者:@winng
本文为作者原创,转载请注明出处:https://www.cnblogs.com/winng/p/django_mysql_driver.html


相关教程