前言
本文使用的源码安装及其排错,下列为其他几种安装方式。
yum安装:
yum install MySQL-python -y
pip安装:
pip install python-mysql
Python安装MySQLdb模块
【1】官网下载合适的版本
https://pypi.org/project/MySQL-python/
或
wget https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip
【2】解压及安装
安装依赖包:
yum -y install rpm-build gcc-c++ mysql-devel python-devel
unzip MySQL-python-1.2.5.zip
cd MySQL-python-1.2.5
find / -name mysql_config
vim site.cfg(取消mysql_config前的注释,并配置为你实际的数据库该文件所在位置)
[options]
# embedded: link against the embedded server library
# threadsafe: use the threadsafe client
# static: link against a static library (probably required for embedded)
embedded = False
threadsafe = True
static = False
# The path to mysql_config.
# Only use this if mysql_config is not on your PATH, or you have some weird
# setup that requires it.
#mysql_config = /usr/local/bin/mysql_config
mysql_config = /app/mysql/bin/mysql_config
# http://stackoverflow.com/questions/1972259/mysql-python-install-problem-using-virtualenv-windows-pip
# Windows connector libs for MySQL. You need a 32-bit connector for your 32-bit Python build.
connector = C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2
python setup.py build
python setup.py install
【3】验证
python中输入import MySQLdb,无报错即为成功
安装过程中的报错及解决
【1】ImportError: libmysqlclient.so.xx
原因:系统找不到名为libmysqlclient.so.xx的库文件
解决方法:
<1>删除生成的build目录
cd MySQL-python-1.2.5
rm -rf build
<2>查找libmysqlclient.so.xx文件的位置
find / -name libmysqlclient.so.xx
<3>将文件发送到默认lib库位置处,可以做个软链接
ln -s /usr/local/mysql/lib/libmysqlclient.so.xx /usr/lib/libmysqlclient.so.xx
<4> /etc/ld.so.conf添加库的位置
include ld.so.conf.d/*.conf
/usr/lib/
/usr/local/lib/
/usr/local/mysql/lib/
重新加载配置:
ldconfig
【2】ImportError: /root/.python-eggs/MySQL_python-1.2.5-py2.7-linux-x86_64.egg-tmp/_mysql.so: undefined symbol: __cxa_pure_virtual
原因:在编译的时候没有成功加载zlib,更换编译器gcc 为g++
解决方法:
<1>删除生成的build目录
cd MySQL-python-1.2.5
rm -rf build
<2>执行build
python setup.py build
复制显示的最后一行:
gcc -pthread -shared build/temp.linux-x86_64-2.7/_mysql.o -L/shang1/test/mysql/lib -lmysqlclient_r -lpthread -lz -lm -lrt -ldl -o build/lib.linux-x86_64-2.7/_mysql.so
<3>更换gcc为g++后执行
g++ -pthread -shared build/temp.linux-x86_64-2.7/_mysql.o -L/shang1/test/mysql/lib -lmysqlclient_r -lpthread -lz -lm -lrt -ldl -o build/lib.linux-x86_64-2.7/_mysql.so
<4>无报错后,执行install
python setup.py install
【3】UserWarning: Module _mysql was already imported from…
原因:你是在解压后的源码包的位置执行的import,模块重复导致报错。
解决方法:
切换的目录执行import即可。