按名称而不是在 cx_Oracle 中的位置获取列值

mik*_*sey 3 python cx-oracle

使用cx_Oracle,我正在从 Oracle 数据库中选择数据。

curs = cxn.cursor()
result = curs.execute(SELECT FirstName, LastName FROM Person)
Run Code Online (Sandbox Code Playgroud)

有没有办法只返回没有数字索引的名字?例如:

for row in result:
    result[0] #will return the first column
Run Code Online (Sandbox Code Playgroud)

我希望做的是将价值称为 result['FirstName']

Ant*_*nga 7

您可以使用行工厂返回响应名称和索引的行。一种简单的方法是使用 collections.namedtuple,如以下代码(使用 cx_Oracle 测试套件设置):

import cx_Oracle
import collections

connection = cx_Oracle.Connection("cx_Oracle/dev@localhost/orcl")
cursor = connection.cursor()
cursor.execute("select * from TestStrings")
names = [c[0] for c in cursor.description]
cursor.rowfactory = collections.namedtuple("TestStrings", names)
for row in cursor:
    print(row)
    print(row[0])
    print(row.STRINGCOL)
Run Code Online (Sandbox Code Playgroud)

您还可以查看 cx_Oracle 存储库中提供的示例,以获取更多灵感。

https://github.com/oracle/python-cx_Oracle/blob/main/samples/rows_as_instance.py

您也可以使用输出类型处理程序来使这一切变得无缝。我稍后会将该示例添加到 cx_Oracle 存储库中。