How can I make cx-oracle bind the results of a query to a dictionary rather than a tuple?

断了今生、忘了曾经 提交于 2019-12-03 05:59:16

问题


Here is my code. I would like to find a way to have results from a query returned as a list of dictionaries rather than list of tuples. It seems like cx_oracle supports this with parts of the documentation talking about 'binding'. Though I can't figure out how it works.

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

回答1:


Bindvars are used to execute query such as

  • By name(given named parameters)

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

will print : ['BOOKID']

  • by position given a list of values

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

To get what you expected you could try something like that:

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



回答2:


Here is a quick and dirty. Feel post a better way.

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


来源:https://stackoverflow.com/questions/4468071/how-can-i-make-cx-oracle-bind-the-results-of-a-query-to-a-dictionary-rather-than

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!