Лучшие способы распечатать имена столбцов при использовании cx_Oracle - PullRequest
9 голосов
/ 07 июня 2010

Найден пример с использованием 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. : -)

Ответы [ 3 ]

14 голосов
/ 18 февраля 2018

Вы можете использовать списки в качестве альтернативы для получения имен столбцов:

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

Поскольку cursor.description возвращает список кортежей из 7 элементов, вы можете получить 0-й элемент, который является именем столбца.

2 голосов
/ 21 июня 2018

Вот код.

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()
2 голосов
/ 25 мая 2011

Исходный код 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
...