使用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]
(名字)的列表,所以我修改了代码:
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 个回答
10
这里是代码。
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()
45
你可以用列表推导式来获取列名,这是一种简单的方法:
col_names = [row[0] for row in cursor.description]
这里,cursor.description 返回的是一个包含7个元素的元组的列表,你可以通过取每个元组的第一个元素来得到列名。
5
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