AndreasT
AndreasT

Reputation: 9801

jython zxJDBC: How to get a dictionary from a cursor?

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

Usually you get a row as list as result of a query:

print resultlist(4)

And you have to know the order of the Columns in the schema beforehand.

How can I get something like

print resultset[CustomerName]

to print the name of a customer?

Upvotes: 3

Views: 1032

Answers (1)

mzjn
mzjn

Reputation: 51012

How about dict_cursor from this question: Django Backend-neutral DictCursor?

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

Upvotes: 2

Related Questions