How to retrieve SQL result column value using column name in Python?(如何在 Python 中使用列名检索 SQL 结果列值?)
问题描述
有没有办法在 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.
这篇关于如何在 Python 中使用列名检索 SQL 结果列值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Python 中使用列名检索 SQL 结果列值?


- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- SQL 临时表问题 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01