目錄
- 環境介紹
- mysqlclient
- pymysql
- mysql-connector-python
參考鏈接:
-
Django 連接MySQL的驅動設定
對于在Django 中連接MySQL 的驅動,有以下三種:
- mysqlclient
- mysql-connector-pythom
- pymysql (建議:這個包已經有一年未升級了,本人不建議使用),
-
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.
- mysql-connector-python
環境介紹
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__.py或settings.py或manage.py里寫入:
import pymysql
pymysql.install_as_MySQLdb()
但是不論在哪里寫都有這樣的報錯(發生位置不一樣),棄之
mysql-connector-python
官方檔案
- 在
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' } } - 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后不報錯了
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/396041.html
標籤:Python
