【问题标题】:Better ways to print out column names when using cx_Oracle使用 cx_Oracle 时打印列名的更好方法
【发布时间】:2011-02-28 14:40:19
【问题描述】:

找到一个使用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](name)的列表,所以我改了代码:

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 初学者的替代品。 :-)

【问题讨论】:

  • 对不起老兄,你自己搞定的;)谢谢

标签: python cx-oracle


【解决方案1】:

您可以使用列表推导作为获取列名的替代方法:

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

由于 cursor.description 返回一个包含 7 个元素的元组列表,因此您可以获得第 0 个元素,即列名。

【讨论】:

    【解决方案2】:

    这里是代码。

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

    【讨论】:

    • 非常感谢,代码创建了一个不错的 CSV 文件。
    【解决方案3】:

    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
    

    【讨论】:

      猜你喜欢
      • 2016-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      • 2015-11-21
      • 1970-01-01
      • 1970-01-01
      • 2012-01-27
      相关资源
      最近更新 更多