2010-06-07 20 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() 

मुझे लगता है कि बेहतर तरीके से बाहर स्तंभों के नाम मुद्रित करने के लिए किया जाएगा। कृपया मुझे पाइथन शुरुआत करने के लिए विकल्प मिलें। :-)

+0

क्षमा करें दोस्त, आपने इसे खुद को खींचा;) Thanx – ant

उत्तर

2

SQLAlchemy source code डेटाबेस आत्मनिरीक्षण के मजबूत तरीकों के लिए एक अच्छा प्रारंभिक बिंदु है। यहाँ है कैसे SQLAlchemy ओरेकल से तालिका नाम को दर्शाता है:

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 की सूची लौटाता है तत्व tuples आप 0 वें तत्व प्राप्त कर सकते हैं जो एक स्तंभ नाम है।

संबंधित मुद्दे