python访问mysql数据库

[size=large]开始python的学习!啦啦啦。

python的几个内建函数:apply(),filter(),map(),reduce()

使用python 访问 mysql数据库。
1,需要安装mysql,之所以需要安装mysql,是因为mysql-python包的编译安装需要读取配置文件。没有安装的话,会报如下错误:EnvironmentError: mysql_config not found
如果mysql安装在其他路径下,可以对mysql_config的文件路径可以指定:
修改setup_posix.py文件,在26行显示地设定mysql_config:mysql_config.path = "/data/mysql/bin/mysql_config"

[img]http://dl.iteye.com/upload/attachment/0071/1228/b51854db-deb7-320c-834b-62b255aa0e76.jpg[/img]

一路安装,默认会安装再/usr/local/mysql下。
2,安装mysq-python包,下载地址为:http://sourceforge.net/projects/mysql-python/
运用python setup.py build ,python setup.py install安装。
不过会报如下错误:

[img]http://dl.iteye.com/upload/attachment/0071/1230/f12a3fdc-298d-3a57-810e-7f32fc86d51e.jpg[/img]
根据提示信息,是缺少gcc,网上查阅资料,
http://waqasshabbir.tumblr.com/post/19073648382/llvm-gcc-4-2-exe-error-on-mac-osx-lion-when-building
通过安装gcc-10.7或者安装xcode可以解决。
本来想安装最新的xcode的,但是app store严重不给力,还有人说有bug啥的。就没有贸然去安装了。gcc-10.7这个据作者说卸载比较麻烦。

3,如果找不到libmysqlclient.18.dylib
则做一个软链接:
sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/

4,访问mysql数据的代码还是比较简单的。
1.导入MySQL模块
import MySQLdb

2.数据库连接 (打开/关闭)
conn = MySQLdb.connect(host="", user="", passwd="", db="")

conn.close()

3.游标 (是python数据库访问的中心)
cursor = conn.cursor()
cursor.execute(insertsql/updatesql/deletesql) #执行更新语句

参数化SQL--带占位符的sql语句
cursor.execute("insert into colors(color, abbr) values(%s, %s)", ('blue', 'bl'))
MySQLdb将所有值视为字符串值,即使其底层数据库类型为bigint, double, date...
cursor.executemany("insert into colors(color, abbr) values(%s, %s)", ('blue', 'bl'), ('red', 'rd'), ('orange', 'oe'))
等价于
cursor.execute("insert into colors(color, abbr) values(%s, %s)", ('blue', 'bl'))
cursor.execute("insert into colors(color, abbr) values(%s, %s)", ('red', 'rd'))
cursor.execute("insert into colors(color, abbr) values(%s, %s)", ('orange', 'oe'))

4.查询
cursor.execute(selectsql)
for row in cursor.fetchall():

获取结果集方法 (如果sql不是一个查询就抛出异常):
1) cursor.fetchall--获取所有结果
2) cursor.fetchone--逐行取出
3) cursor.fetchmany--取出预定义数目的行[/size]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值