Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()
like image 902
Peter Avatar asked Dec 17 '10 05:12

Peter


People also ask

What are bind variables in Oracle?

Bind variables are variables you create in SQL*Plus and then reference in PL/SQL. If you create a bind variable in SQL*Plus, you can use the variable as you would a declared variable in your PL/SQL subprogram and then access the variable from SQL*Plus.

How do you bind variables in Oracle SQL Developer?

You simply have to write a command which starts with keyword VARIABLE followed by the name of your bind variable which is completely user defined along with the data type and data width. That's how we declare a bind variable in Oracle database.

What is cursor execute?

This method executes a SQL query against the database. This is a DB API compliant call. Parameters are substituted using question marks, e.g. "SELECT name FROM table WHERE id=?". The parameter args is a tuple . It returns None on success or raises an exception in the case of an error.


1 Answers

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()
like image 93
rapdum Avatar answered Sep 18 '22 12:09

rapdum