Better ways to print out column names when using cx_Oracle

十年热恋 提交于 2020-02-26 06:36:05

问题


Found an example using cx_Oracle, this example shows all the information of 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()

What I wanted to see was the list of Cursor.description[0](name), so I changed the code:

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()

I think there will be better ways to print out the names of columns. Please get me alternatives to the Python beginner. :-)


回答1:


The SQLAlchemy source code is a good starting point for robust methods of database introspection. Here is how SQLAlchemy reflects table names from 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



回答2:


You can use list comprehension as an alternative to get the column names:

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

Since cursor.description returns a list of 7-element tuples you can get the 0th element which is a column name.




回答3:


Here the code.

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()


来源:https://stackoverflow.com/questions/2988159/better-ways-to-print-out-column-names-when-using-cx-oracle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!