码迷,mamicode.com
首页 > 数据库 > 详细

mac机上python操作mysql数据库

时间:2015-05-27 15:48:09      阅读:303      评论:0      收藏:0      [点我收藏+]

标签:mac   python mysql   traceback   

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

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

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

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

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

python setup.py build

如果出现以下错误:

sh: mysql_config: command not found
Traceback (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 






mac机上python操作mysql数据库

标签:mac   python mysql   traceback   

原文地址:http://blog.csdn.net/y943623901/article/details/46046883

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!