python - 使用 cx_Oracle 时打印列名的更好方法

标签 python cx-oracle

找到一个使用cx_Oracle的例子,这个例子显示了Cursor.description的所有信息。

import cx_Oracle
from pprint import pprint

connection = cx_Oracle.Connection("%s/%s@%s" % (dbuser, dbpasswd, oracle_sid))
cursor = cx_Oracle.Cursor(connection)
sql = "SELECT * FROM your_table"
cursor.execute(sql)
data = cursor.fetchall()
print "(name, type_code, display_size, internal_size, precision, scale, null_ok)"
pprint(cursor.description)
pprint(data)
cursor.close()
connection.close()

我想看的是Cursor.description[0](name)的列表,所以改了代码:

import cx_Oracle
import pprint

connection = cx_Oracle.Connection("%s/%s@%s" % (dbuser, dbpasswd, oracle_sid))
cursor = cx_Oracle.Cursor(connection)
sql = "SELECT * FROM your_table"
cursor.execute(sql)
data = cursor.fetchall()
col_names = []
for i in range(0, len(cursor.description)):
    col_names.append(cursor.description[i][0])
pp = pprint.PrettyPrinter(width=1024)
pp.pprint(col_names)
pp.pprint(data)
cursor.close()
connection.close()

我认为会有更好的方法来打印列名。请给我替代 Python 初学者的方法。 :-)

最佳答案

您可以使用列表理解作为获取列名称的替代方法:

col_names = [row[0] for row in cursor.description]

由于 cursor.description 返回 7 元素元组列表,您可以获得第 0 个元素,即列名。

关于python - 使用 cx_Oracle 时打印列名的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2988159/

相关文章:

python - cx_Oracle : how do I get the ORA-xxxxx error number?

python - python和oracle处理异常握手的正确方法

python - Anaconda 3.5(64 位 Windows)安装 cx_Oracle

python - 如何在python dash_cytoscape中设置同心圆布局参数?

python - 如何将字符串转换为字节数组?

python - 如何搜索子字符串,找到开始和结束,然后检查该数据是否为工作日?

python - cx_oracle 和 python 2.7

python - openpyxl error raise ValueError ('Min value is {0}' .format(self.min)) 在打开带格式的重文件时

Python - 使用单个按键切换 turtle 笔的状态

python - Anaconda:安装本地二进制包到Windows中的conda环境