今天用python连接mysql时报错:
File "/Users/zhbink/Documents/GitHub/Scrapy/ArticleSpider/ArticleSpider/pipelines.py", line 5, in <module>
import MySQLdb
File "/Users/zhbink/opt/anaconda3/envs/django/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module>
from . import _mysql
ImportError: dlopen(/Users/zhbink/opt/anaconda3/envs/django/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.21.dylib
Referenced from: /Users/zhbink/opt/anaconda3/envs/django/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so
Reason: image not found
使用的库是MySQLdb
,遂考虑到可能是我使用的这个python版本与库不兼容。
查阅资料后发现MySQLdb
不兼容py3.5以后的版本。
解决办法:
使用pymysql
代替MySQLdb
步骤:
安装pymysql:pip install pymysql
打开项目__init__.py,或直接在当前py文件最开头添加如下:
import pymysql
pymysql.install_as_MySQLdb()