最新消息:

mac下安装和使用MySQL-python

mac admin 3526浏览 0评论

MySQLPython下载地址:

https://pypi.python.org/pypi/mysql-python/

https://github.com/farcepest/MySQLdb1

第一次执

python setup.py build

报错:

sh: mysql_config: command not found
Traceback (most recent call last):
  File "setup.py", line 18, in <module>
    metadata, options = get_config()
  File "/Users/daodao/Desktop/Mysql/setup_posix.py", line 43, in get_config
    libs = mysql_config("libs_r")
  File "/Users/daodao/Desktop/Mysql/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 = "mysql_config"

 

修改为我本机的mysql_config配置路径:

mysql_config.path = "/usr/local/mysql-5.6.14-osx10.7-x86_64/bin/mysql_config"

 

继续执行

python setup.py build

 

然后还是继续报错,但这次跟Xcode相关:

xcrun: error: active developer path ("/Applications/Xcode.app/Contents/Developer") does not exist, use xcode-select to change
error: command '/usr/bin/clang' failed with exit status 1

 


网上找了半天没有找到解决的办法。我早前曾安装后删除过Xcode

————————————

网上有人说好像是因为环境需要安装gcc,Xcode里面的command_line_tools 支持GGC,不管,先重新按照了下Xcode和command_line_tools,然后继续重复执行上面的操作。

python setup.py clean
python setup.py build
sudo python setup.py install

 

果然没有再报错了。但是问题还在继续,终端进入Python测试效果

import MySQLdb

 

果然还是不顺利。。。报错:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.6-intel.egg/MySQLdb/__init__.py", line 19, in <module>
    import _mysql
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.6-intel.egg/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib
  Referenced from: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.6-intel.egg/_mysql.so
  Reason: image not found

 

咋破。快被折腾坏了

好吧,花了将近4个小时终于搞定这个问题了,最后一步骤的错误问题自问自答:

用vi指令在 User/打开 .bash_profile 文件,这是一个隐藏文件。

vi .bash_profile

 

进入编辑状态,在最后添加

export DYLD_LIBRARY_PATH="/usr/local/mysql/lib"

:w 保存退出bash

重新,切换到Python开发环境下, import MySQLdb 返回正常。

继续在Bash中输入 mysql -uroot

反馈:-bash: mysql: command not found。好吧,由于系统默认会查找/usr/bin下的命令,如果这个命令不在这个目录下,我们需要做的就是映射一个链接到/usr/bin目录下,相当于建立一个链接文件。 首先得知道mysql命令或mysqladmin命令的完整路径,比如mysql的路径是:/usr/local/mysql/bin/mysql,然后执行命令:

ln -s /usr/local/mysql/bin/mysql /usr/bin

 

O了!可以测试一下,在Python的交互式命令行,输入import MySQLdb,如果没有报错,就说明已经安装好。

安装完成

Python数据库的连接

下面的Python代码展示了如何连接数据库,并执行数据库的一些操作:

import MySQLdb

try:
    conn = MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306)
    cur = conn.cursor()

    cur.execute('create database if not exists PythonDB')
    conn.select_db('PythonDB')
    cur.execute('create table Test(id int,name varchar(20),info varchar(20))')

    value = [1,'ACdreamer','student']
    cur.execute('insert into Test values(%s,%s,%s)',value)

    values = []
    for i in range(20):
        values.append((i,'Hello World!','My number is '+str(i)))

    cur.executemany('insert into Test values(%s,%s,%s)',values)
    cur.execute('update Test set name="ACdreamer" where id=3')

    conn.commit()
    cur.close()
    conn.close()
except MySQLdb.Error,msg:
    print "MySQL Error %d: %s" %(msg.args[0],msg.args[1])

 

可以看出,连接数据库大致分为以下步骤:

(1)建立和数据库系统的连接

(2)获取操作游标

(3)执行SQL,创建一个数据库(当然这一步不是必需的,因为我们可以用已经存在的数据库)

(4)选择数据库

(5)进行各种数据库操作

(6)操作完毕后,提交事务(这一步很重要,因为只有提交事务后,数据才能真正写进数据库)

(7)关闭操作游标

(8)关闭数据库连接

当然,如果我们使用已经存在的数据库,那么在获取连接时就可以制定了,比如:

conn = MySQLdb.connect(host=’localhost’, user=’root’, passwd=’root’, db=’PythonDB’)

如果数据库中有中文,为了防止乱码,我们加入属性charset = ‘uft-8’或者’gb2312’,charset要跟数据库的编码一致。

conn = MySQLdb.connect(host=’localhost’, user=’root’, 

       passwd=’root’, db=’PythonDB’,charset=’utf8′) 

下面贴一下常用的函数:

数据库连接对事务操作的方法:commit() 提交    rollback() 回滚

cursor用来执行命令的方法:

callproc(self,procname,args)

用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数

execute(self, query, args)

执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数

executemany(self, query, args)

执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数

nextset(self)

移动到下一个结果集

cursor用来接收返回值的方法:

fetchall(self)

接收全部的返回结果行

fetchmany(self, size=None)

接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据

fetchone(self)

返回一条结果行

scroll(self, value, mode=’relative’)

移动指针到某一行,如果mode=’relative’,则表示从当前所在行移动value条,如果 mode=’absolute’,则表示从结果集的第一行移动value条。

转载请注明:爱开源 » mac下安装和使用MySQL-python

您必须 登录 才能发表评论!