如何在 Python 中使用列名检索 SQL 结果列值?

2021-11-20 00:00:00 python mysql

有没有办法在 Python 中使用列名而不是列索引来检索 SQL 结果列值?我在 mySQL 中使用 Python 3.我正在寻找的语法非常类似于 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.

相关文章