红联Linux门户
Linux帮助

在Ubuntu上安装MySQLdb

发布时间:2015-02-08 21:45:36来源:linux网站作者:linux人

准备用Python写点脚本练练手,于是在Ubuntu上安装Python的MySQLdb,本以为很简单的事,没想到还碰到几个小波折,因此记录一下以备忘。


首先需要安装Python-dev,否则后面编译MySQLdb的时候会报错,找不到头文件:

building '_mysql' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC
 -Dversion_info=(1,2,3,'final',0) -D__version__=1.2.3
-I/u01/mysql/include/mysql -I/usr/include/python2.6 -c _mysql.c
-o build/temp.linux-i686-2.6/_mysql.o -DUNIV_LINUX
In file included from _mysql.c:29:
pymemcompat.h:10: fatal error: Python.h: 没有那个文件或目录
compilation terminated.
error: command 'gcc' failed with exit status 1
sudo apt-get install python-dev


其次需要先安装setuptools,否则MySQLdb无法编译

ImportError: No module named setuptools
setuptools从http://pypi.python.org/pypi/setuptools下载

python setup.py build
sudo python setup.py install

从http://sourceforge.net/projects/mysql-python下载MySQLdb
修改site.cfg将mysql_config指向正确的位置

python setup.py build
sudo python setup.py install


最后还需要安装libmysqlclient-dev,否则import模块的时候会出错

ImportError: libmysqlclient_r.so.16: cannot open shared object file:
No such file or directory
sudo apt-get install libmysqlclient-dev


装完以后,来个hello world式的简单查询

#!/usr/bin/env python
import MySQLdb

db=MySQLdb.connect(host="host_name",db="mysql",user="ningoo",passwd="password")
c=db.cursor()
n=c.execute("select user,host from user")
for row in c.fetchall():
for col in row:
print col


想在服务器上需要运行MYSQLDB,sudo apt-get install python-mysqldb提示安装成功,可是import MySQLdb 提示找不到此模块

sudo apt-get source python-mysqldb,想编译一下,总也不成功,总报错,估计是库不全,

sudo apt-get install python-all-dev

sudo apt-get install libmysqlclient15-dev

sudo apt-get install zlib1g-dev

再重新编译 ,OK,记录在此,以免下次有经验。