January 2000
Intermediate to advanced
672 pages
21h 46m
English
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 dsYou 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, ...Read now
Unlock full access