在Ubuntu上安装MySQLdb

准备用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从这里下载

python setup.py build
sudo python setup.py install

这里下载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

无觅相关文章插件,快速提升流量