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 结果列值?


基础教程推荐
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01