歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> 在Ubuntu上安裝MySQLdb

在Ubuntu上安裝MySQLdb

日期:2017/2/28 16:19:05   编辑: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從這裡下載

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

Copyright © Linux教程網 All Rights Reserved