一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

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~

热门栏目