sql - 如何根据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?请建议。谢谢。
解决方案
如果您想要从您正在查询的表中获取列名,您可以执行以下操作:
我的例子是打印一个 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#
推荐阅读
- c++ - 多维数组会在 C 和/或 C++ 中引起任何问题吗?
- powerbi - Power BI:导入模式 - 备用凭据不起作用
- reactjs - 我希望项目列表中的每个项目都有一个与之匹配的图像
- c++ - 引发异常:读取访问冲突。标准::shared_ptr
:: 运算符 -> (...) 返回 nullptr.,发生 - unity3d - 如何将 Tilemap 添加到预制件中?
- python - 按下按钮时文本未输出到 pygame 屏幕
- java - Java 11:目标org.apache.maven.plugins的执行默认编译:maven-compiler-plugin:3.8.0:编译失败。:NullPointerException
- networking - 为 NAS 创建一个“专用”局域网
- css - 通过 SASS 添加图标时,图标无法在 Firefox 中正确呈现
- c - 自己的 offsetof 实现产生警告