最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Python MySQLdb返回以数据库字段名为键值的字典形式结果集
时间:2015-01-22 编辑:简简单单 来源:一聚教程网
使用Python MySQLdb查询出来的结果集是一个数组形式的,访问格式为数组格式,即:
#...连接数据库
sql = 'select a.id, a.group,a.name, a.apk_id, a.ipa_id, b.name as ipa_name, c.name as apk_name from product a left join file_info b on a.ipa_id = b.id left join file_info c on a.apk_id = c.id;'
conn = MySQLdb.connect(host="localhost",user="atool",passwd="atool",db="atool",charset="utf8")
cursor = conn.cursor()
n = cursor.execute(sql)
r = cursor.fetchall()
for p in app_info:
try:
print('project %d' % p[0])
except Exception,ex:
print Exception,":",ex
continue
访问形式使用[0]这种数组索引来访问,非常难懂不方便。这在PHP中是可以自己定义的
array PDOStatement::fetchAll ([ int $fetch_style [, mixed $fetch_argument [, array $ctor_args = array() ]]] )
通过fetch_style可以配置实用数组下标,还是数据库字段名下面,还是都选择。
实际上,在Python MySQLdb也是可以配置的,只不过配置的地方不是在fetch结果集的时候,而是在数据库连接之后获取cursor的时候,指定一个cursor类型为字典格式即可。如下代码所示:
conn = MySQLdb.connect(host="localhost",user="atool",passwd="atool",db="atool",charset="utf8")
cursor = conn.cursor ( cursorclass = MySQLdb . cursors . DictCursor )
测试一下,即可看到代码效果!Enjoy~
-
下一个: Phalcon框架安装与使用教程介绍
相关文章
- PHP导出数据超时的优化建议解读 10-31
- PHP之mysql位运算解析 10-31
- Laravel实现登录跳转功能解析 10-31
- php双向队列解读 10-31
- Laravel异常上下文解决教程 10-24
- php数组查询元素位置方法介绍 10-24