如何在Python中使用列名检索SQL结果列值? [英] How to retrieve SQL result column value using column name in Python?

查看:195
本文介绍了如何在Python中使用列名检索SQL结果列值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以使用列名而不是Python中的列索引来检索SQL结果列值?我正在将Python 3与mySQL一起使用.我正在寻找的语法非常类似于Java构造:

Is there a way to retrieve SQL result column value using column name instead of column index in Python? I'm using Python 3 with mySQL. The syntax I'm looking for is pretty much like the Java construct:

Object id = rs.get("CUSTOMER_ID"); 

我有一个包含很多列的表,而不断为我需要访问的每一列编制索引确实是一个痛苦.此外,索引使我的代码难以阅读.

I've a table with quite a number of columns and it is a real pain to constantly work out the index for each column I need to access. Furthermore the index is making my code hard to read.

谢谢!

推荐答案

MySQLdb 模块具有 DictCursor :

像这样使用它(摘自使用Python DB-API编写MySQL脚本):

Use it like this (taken from Writing MySQL Scripts with Python DB-API):

cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT name, category FROM animal")
result_set = cursor.fetchall()
for row in result_set:
    print "%s, %s" % (row["name"], row["category"])

编辑:根据user1305650的规定,它也适用于 pymysql .

edit: According to user1305650 this works for pymysql as well.

这篇关于如何在Python中使用列名检索SQL结果列值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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