在Python2.x中访问MySQL数据库可以使用第三方库MySQL-Python(即MySQLdb),但是MySQLdb不支持Python3.x。在Python3.x中,可以使用另一个第三方库MySQLclient作为替代,它是基于MySQL-Python开发的,提供了和前者几乎相同的接口。因此,在两个Python版本下,可以使用相同的代码访问MySQL。

Python2.x中

pip install -i https://pypi.douban.com/simple/ mysql-python

Windows下如果出现错误:

_mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory

提示缺少C++的相关环境,到 http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python 下载对应版本的包。
下载完成之后安装:

F:\Downloads>workon test2
(test2) F:\Downloads>pip install MySQL_python-1.2.5-cp27-none-win_amd64.whl
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
Processing f:\Downloads\mysql_python-1.2.5-cp27-none-win_amd64.whl
Installing collected packages: MySQL-python
Successfully installed MySQL-python-1.2.5

(test2) F:\Downloads>

然后就安装成功了MySQL-python

Python3.x中

pip install -i https://pypi.douban.com/simple/ mysqlclient

同样,Windows下如果出现错误,到 http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient 下载对应版本的包即可。
Python安装MySQL驱动

下载之后安装

F:\Downloads>workon Py3_spider
(Py3_spider) F:\Downloads>pip install mysqlclient-1.4.1-cp37-cp37m-win_amd64.whl
Processing f:\Downloads\mysqlclient-1.4.1-cp37-cp37m-win_amd64.whl
Installing collected packages: mysqlclient
Successfully installed mysqlclient-1.4.1

(Py3_spider) F:\Downloads>

相关文章: