默認狀況下,MySQLdb包是沒有安裝的,不信? 看到相似下面的代碼你就信了。
-bash-3.2# /usr/local/python2.7.3/bin/python get_cnblogs_news.py
Traceback (most recent call last):
File "get_cnblogs_news.py", line 9, in <module>
import MySQLdb
ImportError: No module named MySQLdb
這時咱們就不得不安裝MySQLdb包了。安裝其實也挺簡單,具體步驟以下:
一、下載 MySQL for Python
地址:http://sourceforge.net/projects/mysql-python/files/mysql-python/
我這裏安裝的是1.2.3版本
wget http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.3/MySQL-python-1.2.3.tar.gz
二、解壓
tar zxvf MySQL-python-1.2.3.tar.gz
三、安裝
$ cd MySQL-python-1.2.3
$ python setup.py build
不過在python setup.py build時報錯:
ImportError: No module named setuptools
ubuntu下安裝:
sudo apt-get install python-setuptools
python-setuptools : Python Distutils Enhancements (setuptools compatibility)
而後再次python setup.py build,又報錯:
EnvironmentError: mysql_config not found
由於mysql_config是屬於MySQL開發用的文件,而使用apt-get安裝的MySQL是沒有這個文件的,因而在包安裝器裏面尋找
sudo apt-get install libmysqld-dev
libmysqld-dev : MySQL embedded database development files
再次運行python setup.py build,報錯:
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/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-i686-2.7/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -DUNIV_LINUX -DUNIV_LINUX
In file included from _mysql.c:29:0:
pymemcompat.h:10:20: fatal error: Python.h: No such file or directory
解決方案,
sudo apt-get install python-dev
python-dev : header files and a static library for Python (default)
而後就按照README裏的:
pythonsetup.pybuild
sudo python setup.py install
測試:
>>>import MySQLdb
沒有報錯便可。
參考:
http://blog.csdn.net/guzicheng/article/details/5884106
http://be-evil.org/post-185.html
http://hi.baidu.com/hevensun/blog/item/3b6e313fe8515df154e7238f.html
http://stackoverflow.com/questions/1449130/how-to-install-mysqldb-package-importerror-no-module-named-setuptools
http://www.cnblogs.com/objdump/archive/2011/11/03/mysql_python_install_error.html
html