O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Data as Rows

There are several useful ways to represent data. The most obvious is as rows. The Python format for data as rows returned from database cursors is a list of tuples.

This is such a common representation that we’ll wrap it in a class called DataSet . The class doesn’t serve to hide the data; it’s just a convenient place to hang a load of data-manipulation methods (as well as to keep the field names). Here’s part of its definition, showing how to construct a DataSet and display its contents:

class DataSet:
    "wrapper around a tabular set of data"
    def __init__(self):
        self.data = []
        self.fieldnames = []
        
    def pp(self):
        "Pretty-print a row at a time - nicked from Gadfly"
        from string import join
        stuff = [repr(self.fieldnames)] + map(repr, self.data)
        print join(stuff, "\n")
        
def DataSetFromCursor(cursor):
    " a handy constructor"
    ds = DataSet()
    ds.fieldnames = getFieldNames(cursor)
    ds.data = cursor.fetchall()
    return ds

You can use this as follows:

>>> import ODBC.Windows >>> conn = ODBC.Windows.Connect('PYDBDEMOS') >>> cursor = conn.cursor() >>> cursor.execute('SELECT ClientID, PeriodEnding, Consultant, Hours FROM Invoices') >>> import laundry >>> ds = laundry.DataSetFromCursor(cursor) >>> cursor.close() >>> conn.close() >>> ds.pp() ('ClientID', 'PeriodEnding', 'Consultant', 'Hours') ('MEGAWAD', 1999-04-18 00:00:00.00, 'Joe Hacker', 42.0) ('MEGAWAD', 1999-04-18 00:00:00.00, 'Arthur Suit', 24.0) ('MEGAWAD', 1999-04-25 00:00:00.00, 'Joe Hacker', 57.0) ('NOSHCO', 1999-04-25 00:00:00.00, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required