Using cx_Oracle
,我正在从 Oracle 数据库中选择数据。
curs = cxn.cursor()
result = curs.execute(SELECT FirstName, LastName FROM Person)
有没有办法只返回名字而不返回数字索引?例如:
for row in result:
result[0] #will return the first column
我希望做的是将这个值称为result['FirstName']
您可以使用行工厂返回响应名称和索引的行。一种简单的方法是使用 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)
您还可以查看 cx_Oracle 存储库中提供的示例,以获得进一步的灵感。
https://github.com/oracle/python-cx_Oracle/blob/main/samples/rows_as_instance.py https://github.com/oracle/python-cx_Oracle/blob/main/samples/rows_as_instance.py
您也可以使用输出类型处理程序来使这一切变得无缝。稍后我会将该示例添加到 cx_Oracle 存储库中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)