Python - 使用MySQLdb

最近学着玩python和django框架,学到连接数据库,居然给我报导入数据库失败,花了3个小时的功夫度娘+自行解决终于成功了,特此记录,帮助和我一样的python新人少走一些弯路。

第一步,python使用mysql需要安装mysql for python支持包:

前往http://sourceforge.net/projects/mysql-python/下载最新版本,完成后执行编译和安装:

$ 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

可能出现的问题,报错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
再次执行build和install命令
第二步,安装MySQL-Python:

pip是python的包管理工具,提供了安装、升级、列出、卸载包等功能,想要在Python中使用mysql,必须为Python安装MySQL-Python。

安装pip包管理器(具体pip的命令使用可参考这里):

$ easy_install pip

然后就是安装MySQLdb了(记录了卸载命令uninstall,咱们执行install就好):

$ pip install MySQL-python
$ pip uninstall MySQL-python

安装结束后,进入python解释器检查安装状态:

$ python
$ import _mysql

可能出现的错误一:

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

可能出现的错误二:

Traceback (most recent call last):
File "", line 1, in 
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

插入数据至末尾:

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

再次检查安装状态。

你可能感兴趣的:(Python - 使用MySQLdb)