在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


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

5条评论

  • At 2010.11.23 09:01, 文通 said:

    libmysqlclient-dev 可以不装的,直接在/etc/ld.so.conf 里面加入 /XXX/mysql/lib/mysql 这个目录就行了,然后ldconfig 一下就OK了

    • At 2010.11.23 09:48, lasu said:

      还没试过自己编译,我是用 apt-get install python-mysqldb 装的。

      • At 2011.07.13 11:53, tenger13 said:

        谢谢了。。初学PYTHON,装得蛋疼。

        • At 2012.08.22 11:46, Xrong said:

          多谢了。。。

          • At 2013.01.22 10:02, Chris said:

            try apt-get “python-mysql”, “python-mysqldb”, “mysql-python”
            finally, one will work


            (Required)
            (Required, will not be published)