2010-06-07 18 views
6

Tìm thấy một ví dụ sử dụng cx_Oracle, ví dụ này hiển thị tất cả thông tin của Cursor.description.Cách tốt hơn để in ra tên cột khi sử dụng 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() 

Những gì tôi muốn thấy là danh sách các Cursor.description[0] (tên), vì vậy tôi đã thay đổi mã:

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

Tôi nghĩ rằng sẽ có cách tốt hơn để in ra tên của cột. Hãy đưa tôi lựa chọn thay thế cho người mới bắt đầu Python. :-)

+0

Xin lỗi bạn, bạn đã tự đóng đinh bản thân mình;) Thanx – ant

Trả lời

2

SQLAlchemy source code là điểm khởi đầu tốt cho các phương pháp mạnh mẽ về nội tâm cơ sở dữ liệu. Sau đây là cách SQLAlchemy phản ánh tên bảng từ 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

Bạn có thể sử dụng danh sách hiểu như một sự thay thế để có được các tên cột:

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

Kể từ cursor.description trả về một danh sách các 7- tuple phần tử bạn có thể lấy phần tử thứ 0 là một tên cột.

Các vấn đề liên quan