mac机上python操作mysql数据库

来源:互联网 发布:数学问题搜索软件 编辑:程序博客网 时间:2024/06/06 12:38

为了用DB-API编写MySQL脚本,必须确保已经安装了MySQL。复制以下代码,并执行:

import MySQLdb
如果执行后的输出结果如下所示,意味着你没有安装 MySQLdb 模块:

Traceback (most recent call last):  File "./hello.py", line 3, in <module>    import MySQLdbImportError: No module named MySQLdb

可以访问:https://pypi.python.org/pypi/MySQL-python从这里可选择适合您的平台的安装包,分为预编译的二进制文件和源代码安装包。

如果选择二进制文件发行版本的话,安装过程基本安装提示即可完成。如果从源代码进行安装的话,先下载源码然后解压缩,进入解压缩后的目录并执行:

python setup.py build

如果出现以下错误:

sh: mysql_config: command not foundTraceback (most recent call last):  File "setup.py", line 17, in <module>    metadata, options = get_config()  File "/Users/macbook/Downloads/MySQL-python-1.2.5/setup_posix.py", line 43, in get_config    libs = mysql_config("libs_r")  File "/Users/macbook/Downloads/MySQL-python-1.2.5/setup_posix.py", line 25, in mysql_config    raise EnvironmentError("%s not found" % (mysql_config.path,))EnvironmentError: mysql_config not found

则去掉mysql_config=XXX的注释,并改成mysql_config = /usr/bin/mysql_config(以mysql_config文件所在机器上的目录为准,如果不知道其目录,可以使用sudo find / -name mysql_config命令查找)

完成该步骤之后可能仍然会出错:

Traceback (most recent call last):  File "./hello.py", line 3, in <module>    import MySQLdb  File "build/bdist.macosx-10.10-intel/egg/MySQLdb/__init__.py", line 19, in <module>  File "build/bdist.macosx-10.10-intel/egg/_mysql.py", line 7, in <module>  File "build/bdist.macosx-10.10-intel/egg/_mysql.py", line 6, in __bootstrap__ImportError: dlopen(/Users/macbook/.python-eggs/MySQL_python-1.2.5-py2.7-macosx-10.10-intel.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib  Referenced from: /Users/macbook/.python-eggs/MySQL_python-1.2.5-py2.7-macosx-10.10-intel.egg-tmp/_mysql.so  Reason: image not found

此时,需要执行命令

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

注意,该软连接的实际目录部分以自己机器上的目录为准


测试代码:

import MySQLdb# 打开数据库连接db = MySQLdb.connect("dburl","username","password","dbname" )# 使用cursor()方法获取操作游标 cursor = db.cursor()# 使用execute方法执行SQL语句cursor.execute("SELECT VERSION()")# 使用 fetchone() 方法获取一条数据库。data = cursor.fetchone()print "Database version : %s " % data# 关闭数据库连接db.close()

执行结果:

Database version : 5.6.16-log 






0 0
原创粉丝点击