最近學著玩python和django框架,學到連接數(shù)據(jù)庫,居然給我報導入數(shù)據(jù)庫失敗,花了3個小時的功夫度娘+自行解決終于成功了,特此記錄,幫助和我一樣的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)的問題,報錯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的包管理工具,提供了安裝、升級、列出、卸載包等功能,想要在Python中使用mysql,必須為Python安裝MySQL-Python。
安裝pip包管理器(具體pip的命令使用可參考這里):
$ easy_install pip
然后就是安裝MySQLdb了(記錄了卸載命令uninstall,咱們執(zhí)行install就好):
$ pip install MySQL-python
$ pip uninstall MySQL-python
安裝結(jié)束后,進入python解釋器檢查安裝狀態(tài):
$ python
$ import _mysql
可能出現(xiàn)的錯誤一:
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)的錯誤二:
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)。