Using dtuple for Flexible Access to Query Results
Credit: Steve Holden
Problem
You want flexible access to sequences, such as the rows in a database query, by either name or column number.
Solution
Rather than coding your own solution, it’s often
more clever to reuse a good existing one. For this
recipe’s task, a good existing solution is packaged
in Greg Stein’s dtuple module:
import dtuple import mx.ODBC.Windows as odbc flist = ["Name", "Num", "LinkText"] descr = dtuple.TupleDescriptor([[n] for n in flist]) conn = odbc.connect("HoldenWebSQL") # Connect to a database curs = conn.cursor( ) # Create a cursor sql = """SELECT %s FROM StdPage WHERE PageSet='Std' AND Num<25 ORDER BY PageSet, Num""" % ", ".join(flist) print sql curs.execute(sql) rows = curs.fetchall( ) for row in rows: row = dtuple.DatabaseTuple(descr, row) print "Attribute: Name: %s Number: %d" % (row.Name, row.Num or 0) print "Subscript: Name: %s Number: %d" % (row[0], row[1] or 0) print "Mapping: Name: %s Number: %d" % (row["Name"], row["Num"] or 0) conn.close( )
Discussion
Novice Python programmers are often deterred from using databases
because query results are presented by DB API-compliant modules as a
list of tuples. Since these can only be numerically subscripted, code
that uses the query results becomes opaque and difficult to maintain.
Greg Stein’s dtuple module,
available from http://www.lyra.org/greg/python/dtuple.py,
helps by defining two useful classes:
TupleDescriptor and DatabaseTuple.
The TupleDescriptor ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access