如何让cx-oracle将查询结果绑定到字典而不是元组?

时间:2010-12-17 05:50:00

标签: python sql database oracle cx-oracle

这是我的代码。我想找到一种方法,将查询结果作为字典列表而不是元组列表返回。似乎cx_oracle支持这一点,部分文档谈论'绑定'。虽然我无法弄清楚它是如何运作的。

def connect():  
    dsn = cx_Oracle.makedsn("host", 1521, "sid")
    orcl = cx_Oracle.connect('scott/tiger@' + dsn)
    curs = orcl.cursor()
    sql = "select * from sometable"
    curs.execute(sql)
    result = curs.fetchall()
    for row in result:
        print row[13] #CATEGORY field order
        print row['CATEGORY'] # <- I want this to work ('CATEGORY' is the name of a field in the 'sometable' table)
    curs.close()

2 个答案:

答案 0 :(得分:16)

Bindvars用于执行查询,例如

  • 按名称(给定命名参数)

    cursor = self.db.cursor()
    cursor.execute("SELECT bookName, author from books where Id=:bookId" , bookId="155881")
    print cursor.bindnames()
    

将打印:['BOOKID']

  • 按位置给出值列表

    cursor = self.db.cursor()
    cursor.prepare("insert into books (bookId,title,author,price) values(:1, :2, :3, :4)")
    cursor.executemany(None, listOfbookwhichAreTuppleOf4Field )
    

为了得到你所期望的,你可以尝试类似的东西:

def connect():  
    dsn = cx_Oracle.makedsn("host", 1521, "sid")
    orcl = cx_Oracle.connect('scott/tiger@' + dsn)
    curs = orcl.cursor()
    sql = "select * from sometable"
    curs.execute(sql)
    desc = [d[0] for d in curs.description]
    result = [dict(zip(desc,line)) for line in curs]
    curs.close()

答案 1 :(得分:0)

这是一个快速而又脏的。感觉发布更好的方式。

def connect():  
    dsn = cx_Oracle.makedsn("host", 1521, "sid")
    orcl = cx_Oracle.connect('scott/tiger@' + dsn)
    curs = orcl.cursor()
    sql = "select * from sometable"
    curs.execute(sql)
    fieldNumber = 0
    fieldNames={}
    for desc in curs.description:
        fieldNames[desc[0]]=fieldNumber
        fieldNumber+=1
    result = curs.fetchall()
    for row in result:
        print str(row[fieldNames['CATEGORY']])
    curs.close()