Iterate through properties

781 views
Skip to first unread message

matt connolly

unread,
Feb 3, 2009, 8:33:12 PM2/3/09
to pyodbc
Is there a way to iterate through the properties (attributes) of a
pyodbc.Row ?

If I run:

cursor.execute("SELECT * FROM MyTable")
row = cursor.fetchone()

then I can access the fields like `row.field1` which is great.

But when I do:

for field in row:

matt connolly

unread,
Feb 3, 2009, 8:34:11 PM2/3/09
to pyodbc
sorry, here is rest:

when I do:

for field in Row:
print field

field contains the values.

Is there a way to iterate over the row and get the field names, like a
dict?

mkleehammer

unread,
Feb 4, 2009, 10:04:16 AM2/4/09
to pyodbc
Absolutely. The way specified in the DB API (and therefore portable
to other db libraries) is to use cursor.description, which is a tuple
of tuples, documented here: http://code.google.com/p/pyodbc/wiki/Cursor

The first item in the tuples is the column names, so you can extract
them like so:

cols = [ t[0] for t in cursor.description ]

You could then do something like:

for name, value in zip(cols, row):
print '%s: %s' % (name, value)

I created the Row class to be useful even after the cursor and
connection are closed, so I added the same tuple to all rows as
Row.cursor_description. Apparently I forgot to make the Row wiki
page, but you can see the API documentation by executing help
(pyodbc.Row).

BTW, the Row internals are specially designed to use very little
memory. I use Rows where I would have to create tiny classes or
structs in languages like Java and C/C++. The row names and the
cursor_description are shared by all rows from the same execute call,
so they use less memory than if you created separate objects, one for
each row.


matt connolly

unread,
Feb 4, 2009, 5:52:18 PM2/4/09
to pyodbc
Thanks!

Row.cursor_description is perfect for my needs.

Don't know how I missed it in the help()....

Great to know about the Row memory sharing.
Reply all
Reply to author
Forward
0 new messages