在使用python3连接MySQL的时候出现了 ‘ModuleNotFoundError: No module named ‘MySQLdb’’错误。
为了加深记忆,将问题解决过程总结如下:
1、环境:OS X操作系统,Python 3.7.3。
2、在python文件中引入数据库模块,运行报错
#! /usr/bin/python
# coding: utf-8
# 连接数据库 mysql -u root -p
import MySQLdb
print('sql')
报错内容如下:
2、根据提示安装MySQL-python
pip install MySQL-python
运行安装命令,继续报错,具体报错内容如下,
ERROR: Command errored out with exit status 1:
command: /Users/apple/anaconda3/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/82/g066n2jx5s98h8l5s1r2f4pm0000gn/T/pip-install-s7hkgu37/mysql-python/setup.py'"'"'; __file__='"'"'/private/var/folders/82/g066n2jx5s98h8l5s1r2f4pm0000gn/T/pip-install-s7hkgu37/mysql-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/82/g066n2jx5s98h8l5s1r2f4pm0000gn/T/pip-pip-egg-info-5g06sc7q
cwd: /private/var/folders/82/g066n2jx5s98h8l5s1r2f4pm0000gn/T/pip-install-s7hkgu37/mysql-python/
Complete output (7 lines):
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/private/var/folders/82/g066n2jx5s98h8l5s1r2f4pm0000gn/T/pip-install-s7hkgu37/mysql-python/setup.py", line 13, in <module>
from setup_posix import get_config
File "/private/var/folders/82/g066n2jx5s98h8l5s1r2f4pm0000gn/T/pip-install-s7hkgu37/mysql-python/setup_posix.py", line 2, in <module>
from ConfigParser import SafeConfigParser
ModuleNotFoundError: No module named 'ConfigParser'
----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
3、依据报错提示信息安装ConfigParser
pip install ConfigParser
安装成功之后,运行代码,依然提示上面的报错信息
4、查找原因
这是因为 MySQL-python 不支持 Python3
python3使用mysqlclient模块替代了python2的 mysqldb模块
【解决方法1】
安装mysqlclient模块
pip install mysqlclient
然后就可以正常运行了
【解决方法2】
安装pymysql模块
pip install pymysql
5、如果还有报错,可能是原因是,需要安装mysql,且升级pip版本