时间:2021-07-01 10:21:17 帮助过:30人阅读
执行以下语句:
brew install mysql-connector-c
二、数据库连接
出现以下错误提示:
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
修改setup_posix.py文件,代码如下
mysql_config.path = "/Applications/MAMP/Library/bin/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
注意:该软连接的实际目录部分以自己机器上的目录为准
另外:MAMP出现如下错误提示:
ERROR 2002 (HY000): Can‘t connect to local MySQL server through socket ‘/tmp/mysql.sock‘
找不到socket文件,查找本机文件所在位置
sudo find / -name mysql.sock
将文件地址作为参数传递到数据库连接语句
con=MySQLdb.connect(host=‘localhost‘,user=‘root‘,passwd=‘root‘,db=‘StudentDB‘,port=3306,unix_socket="/Applications/MAMP/tmp/mysql/mysql.sock",charset=‘utf8‘)
三、实例:
以下实例链接Mysql的StudentDB数据库:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import MySQLdb
import sys
import sys
reload(sys)
sys.setdefaultencoding(‘utf-8‘)
con=MySQLdb.connect(host=‘localhost‘,user=‘root‘,passwd=‘root‘,db=‘StudentDB‘,port=3306,unix_socket="/Applications/MAMP/tmp/mysql/mysql.sock",charset=‘utf8‘)
#获取 mysql 的链接对象
with con:
#获取执行查询的对象
cur = con.cursor()
#执行那个查询,这里用的是 select 语句
cur.execute("SELECT * FROM Student")
#使用 cur.rowcount 获取结果集的条数
numrows = int(cur.rowcount)
#循环 numrows 次,每次取出一行数据
for i in range(numrows):
#每次取出一行,放到 row 中,这是一个元组(id,name)
row = cur.fetchone()
#直接输出两个元素
print row[0], row[1]
MAMP中Python安装MySQLdb
标签:安装mysql utf-8 height host 10.10 pytho cbo log 安装