为方便在Linux下使用Python访问Mysql数据库,因此需要先装一个访问Mysql的包,即MySQL-python-1.2.5。
先从https://pypi.org/project/MySQL-python/ 下载上传至服务器/tmp 目录
解压
gunzip MySQL-python-1.2.5.zip
进入包目录、编译、安装
cd /tmp/MySQL-python-1.2.5
# python setup.py build
running build
running build_py
copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb
running build_ext
building '_mysql' extension
gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/local/mysql/include -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o
_mysql.c:29:20: fatal error: Python.h: No such file or directory
#include "Python.h"
^
compilation terminated.
error: command 'gcc' failed with exit status 1
这里报错了,提示缺少Python.h文件,经常是缺少python-devel依赖包
在网站http://pkgs.org 下载对应版本的安装包,上传至服务器并安装
# rpm -Uvh python-devel-2.7.5-76.el7.x86_64.rpm --nodeps
因为我这里的Python版本是2.7.5-68,所以这里使用了 -Uvh --nodeps强制更新,一般情况下版本一致用 -ivh 安装即可。
重新编译、安装通过
# python setup.py build
# python setup.py install
...(略)
Installed /usr/lib64/python2.7/site-packages/MySQL_python-1.2.5-py2.7-linux-x86_64.egg
Processing dependencies for MySQL-python==1.2.5
Finished processing dependencies for MySQL-python==1.2.5
进入Pyhton导入Mysqldb包,报错,提示缺失libmysqlclient.so.20动态库,如下
>>> import MySQLdb
/usr/lib64/python2.7/site-packages/MySQL_python-1.2.5-py2.7-linux-x86_64.egg/_mysql.py:3: UserWarning: Module _mysql was already imported from /usr/lib64/python2.7/site-packages/MySQL_python-1.2.5-py2.7-linux-x86_64.egg/_mysql.pyc, but /tmp/MySQL-python-1.2.5 is being added to sys.path
Traceback (most recent call last):
File "
File "MySQLdb/__init__.py", line 19, in
import _mysql
File "build/bdist.linux-x86_64/egg/_mysql.py", line 7, in
File "build/bdist.linux-x86_64/egg/_mysql.py", line 6, in __bootstrap__
ImportError: libmysqlclient.so.20: cannot open shared object file: No such file or directory
错误的原因是未能引入libmysqlclient.so.20库,
通过 find / -name libmysqlclient.so.20 查找库文件存在,于是建立链接:
ln -s /usr/local/mysql/lib/libmysqlclient.so.20 /usr/lib64/libmysqlclient.so.20
问题解决。
>>>
>>> import MySQLdb
>>>