我如何使cx-oracle将查询的结果绑定到字典而不是元组? [英] How can I make cx-oracle bind the results of a query to a dictionary rather than a tuple?

查看:800
本文介绍了我如何使cx-oracle将查询的结果绑定到字典而不是元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

Bindvars用于执行查询,例如

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


将打印:['BOOKID']

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 )


你可以尝试这样的:

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

这篇关于我如何使cx-oracle将查询的结果绑定到字典而不是元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆