如何让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()
    
已邀请:
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()
    
这是一个快速和肮脏的。感觉发布更好的方式。
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()
    

要回复问题请先登录注册