2010-06-07 31 views
6

使用cx_Oracle發現一個示例,此示例顯示Cursor.description的所有信息。使用cx_Oracle時更好的打印列名稱的方法

import cx_Oracle 
from pprint import pprint 

connection = cx_Oracle.Connection("%s/%[email protected]%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/%[email protected]%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初學者。 :-)

+0

對不起,你自己釘了;)Thanx – ant 2017-09-13 06:17:43

回答

2

SQLAlchemy source code是強健的數據庫內省方法的一個很好的起點。這裏是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 
1

您可以使用列表理解來替代獲得列名:

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

由於cursor.description中返回7-名單元素元組可以得到第0個元素,它是一個列名。