2010-06-07 29 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个元素,它是一个列名。