18

找到了一个使用 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 初学者的替代品。:-)

4

3 回答 3

37

您可以使用列表推导作为获取列名的替代方法:

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

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

于 2018-02-18T17:20:13.100 回答
9

这里是代码。

import csv
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()
于 2018-06-21T08:22:39.910 回答
4

SQLAlchemy 源代码是强大的数据库自省方法的良好起点。下面是 SQLAlchemy 如何反映来自 Oracle 的表名:

SELECT table_name FROM all_tables
WHERE nvl(tablespace_name, 'no tablespace') NOT IN ('SYSTEM', 'SYSAUX')
AND OWNER = :owner
AND IOT_NAME IS NULL
于 2011-05-25T17:12:49.707 回答