Jython zxJDBC: How to get dictionary from cursor?

I am using JDBC to connect my jython to a heterogeneous set of databases. Using the cursor, I get the rows in the form of a list, and the cursor also knows the metadata (cursor.description).

Usually you get the string as a list as a result of the query:

print resultlist(4)

And you should know in advance the order of the columns in the schema.

How can i get something like

print resultset[CustomerName]

to print customer name?

+3
source share
1 answer

How about dict_cursorfrom this question: Django Backend-neutral DictCursor ?

Short description of what works for me (Jython 2.5.2):

def dict_cursor(cursor):
    description = [x[0] for x in cursor.description]
    for row in cursor:
        yield dict(zip(description, row))

conn = zxJDBC.connect(db, user, pwd, driver)
cursor = conn.cursor()

query = "..."
cursor.execute(query)

dc = dict_cursor(cursor)
for d in dc:
    print d["SomeColumnName"]
    ...

cursor.close()
conn.close()
+2
source

All Articles