首页 > 解决方案 > 如何根据python中的列名引用值

问题描述

我正在尝试从 SQL 查询中提取和读取数据。以下是来自 SQL 开发人员的示例数据:

target_name    expected_instances   environment   system_name         hostname
--------------------------------------------------------------------------------------  
ORAUAT_host1   1                    UAT           ORAUAT_host1_sys    host1.sample.net
ORAUAT_host2   1                    UAT           ORAUAT_host1_sys    host2.sample.net 

通常我将 system_name 传递给查询(它具有 system_name 的绑定变量)并将数据作为列表获取,但不是列名。Python中有没有办法检索数据以及列名和引用值,列名如target_name [0]给出值ORAUAT_host1?请建议。谢谢。

标签: sqlpython-3.xoracle

解决方案


如果您想要从您正在查询的表中获取列名,您可以执行以下操作:

我的例子是打印一个 csv 文件

import os
import sys
import cx_Oracle 

db = cx_Oracle.connect('user/pass@host:1521/service_name')
SQL = "select * from dual"
print(SQL)
cursor = db.cursor()
f = open("C:\dual.csv", "w")
writer = csv.writer(f, lineterminator="\n", quoting=csv.QUOTE_NONNUMERIC)
r = cursor.execute(SQL)

#this takes the column names
col_names = [row[0] for row in cursor.description]

writer.writerow(col_names)

for row in cursor:
   writer.writerow(row)
f.close()

打印列的方式是使用游标对象的方法描述

Cursor.description 此只读属性是一个 7 项序列的序列。这些序列中的每一个都包含描述一个结果列的信息:(名称、类型、显示大小、内部大小、精度、比例、null_ok)。对于不返回行的操作或游标尚未通过 execute() 方法调用的操作,此属性将为 None。

该类型将是在模块级别定义的数据库类型常量之一。

https://cx-oracle.readthedocs.io/en/latest/api_manual/cursor.html#


推荐阅读