最近學(xué)著玩python和django框架忆植,學(xué)到連接數(shù)據(jù)庫小渊,居然給我報(bào)導(dǎo)入數(shù)據(jù)庫失敗法褥,花了3個(gè)小時(shí)的功夫度娘+自行解決終于成功了,特此記錄酬屉,幫助和我一樣的python新人少走一些彎路半等。
第一步,python使用mysql需要安裝mysql for python支持包:
前往http://sourceforge.net/projects/mysql-python/下載最新版本呐萨,完成后執(zhí)行編譯和安裝:
$ wget http://sourceforge.net/projects/mysql-python/files/latest/download
$ tar -xvzf MySQL-python-1.2.4b4.tar.gz
$ cd MySQL-python-1.2.4b4
$ python setup.py build
$ python setup.py install
可能出現(xiàn)的問題杀饵,報(bào)錯(cuò)EnvironmentError: mysql_config not found,解決方法:
獲得mysql_config的位置谬擦,如:/usr/local/mysql/bin/mysql_config
修改MySQL-python-1.2.4b4/site.cfg
去掉mysql_config=XXX注釋,并改成mysql_config=/usr/local/mysql/bin/mysql_config
再次執(zhí)行build和install命令
第二步切距,安裝MySQL-Python:
pip是python的包管理工具,提供了安裝惨远、升級(jí)谜悟、列出、卸載包等功能北秽,想要在Python中使用mysql葡幸,必須為Python安裝MySQL-Python。
安裝pip包管理器(具體pip的命令使用可參考這里):
$ easy_install pip
然后就是安裝MySQLdb了(記錄了卸載命令uninstall贺氓,咱們執(zhí)行install就好):
$ pip install MySQL-python
$ pip uninstall MySQL-python
安裝結(jié)束后蔚叨,進(jìn)入python解釋器檢查安裝狀態(tài):
$ python
$ import _mysql
可能出現(xiàn)的錯(cuò)誤一:
Traceback (most recent call last):
File "", line 1, in
ImportError: dlopen(/Library/Python/2.7/site-packages/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib
Referenced from: /Library/Python/2.7/site-packages/_mysql.so
Reason: unsafe use of relative rpath libmysqlclient.18.dylib in /Library/Python/2.7/site-packages/_mysql.so with restricted binary
解決方法:
$ sudo install_name_tool -change libmysqlclient.18.dylib /usr/local/mysql/lib/libmysqlclient.18.dylib /Library/Python/2.7/site-packages/_mysql.so
可能出現(xiàn)的錯(cuò)誤二:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: dlopen(/Library/Python/2.7/site-packages/_mysql.so, 2): no suitable image found. Did find:
/Library/Python/2.7/site-packages/_mysql.so: mach-o, but wrong architecture
解決方法:
$ vim ~/.bash_profile
插入數(shù)據(jù)至末尾:
export DYLD_LIBRARY_PATH="/usr/local/mysql/lib"
export VERSIONER_PYTHON_PREFER_64_BIT=yes
export VERSIONER_PYTHON_PREFER_32_BIT=no
更新文件:
$ source ~/.bash_profile
再次檢查安裝狀態(tài)。