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

查看:44
本文介绍了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天全站免登陆