Python:使用mysqldb导入MySQL表作为字典吗? [英] Python: use mysqldb to import a MySQL table as a dictionary?

查看:75
本文介绍了Python:使用mysqldb导入MySQL表作为字典吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都知道如何使用mysqldb将具有很多行的MySQL表转换为Python中的字典对象列表吗?

Anyone know how I can use mysqldb to turn a MySQL table, with lots of rows, into a list of dictionary objects in Python?

我的意思是将一组带有行"a","b"和"c"的MySQL行转换为一个看起来像这样的Python对象:

I mean turning a set of MySQL rows, with columns 'a', 'b', and 'c', into a Python object that that looks like this:

data = [ { 'a':'A', 'b':(2, 4), 'c':3.0 }, { 'a':'Q', 'b':(1, 4), 'c':5.0 }, { 'a':'T', 'b':(2, 8), 'c':6.1 } ]

谢谢:)

推荐答案

MySQLdb为此提供了一个单独的游标类DictCursor.您可以将要使用的游标类传递给MySQLdb.connect():

MySQLdb has a separate cursor class for this, the DictCursor. You can pass the cursor class you want to use to MySQLdb.connect():

import MySQLdb.cursors
MySQLdb.connect(host='...', cursorclass=MySQLdb.cursors.DictCursor)

这篇关于Python:使用mysqldb导入MySQL表作为字典吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆