Loading select queries into objects

Steve Holden sholden at holdenweb.com
Mon Jun 18 12:08:56 EDT 2001


>From http://www.lyra.org/greg/python/:

"""dtuple.py
This module wraps up return tuples from the fetch* methods in the Python
Database API. Using this class, the return tuples can be treated as tuples,
dictionaries, or objects with attributes corresponding to the column names.

The module is memory efficient -- a "tuple descriptor" is shared across all
result rows, and the result row "wrapper" is very lightweight. The speed is
quite reasonable.
"""

Thanks to Greg Stein for an excellent solution to this problem.

regards
 Steve
--
http://www.holdenweb.com/


"Graham Ashton" <graham at coms.com> wrote in message
news:yCmX6.1448$h45.8877 at news.uk.colt.net...
> Hi. I've just started playing with database access from Python and have
> stumbled across yet another hole in my knowledge of Python idioms.
>
> I've got a class that has an attribute for each column in a database
> table, and an accessor method that sets the value of each attribute. I
> then populate the attributes with the result of a database query.
>
> Here's an example:
>
>     query = """
>         SELECT column1, column2, some_column
>           FROM a_table
>     """
>
>     cursor = self.db.cursor()
>     cursor.execute(query)
>     tup = cursor.fetchone()
>
>     self.column1(tup[0]) # this could be better!
>     self.column2(tup[1])
>     self.some_column(tup[2])
>
> What I'm wondering is; is there an idiomatic way of applying the values
> in a tuple to a list of functions? In Perl I'd use map(), but I'm not
> sure if there's a "cleaner" way in Python.
>
> When the number of columns grows large the above is not only ugly, but a
> nightmare to maintain.
>
> Thanks.






More information about the Python-list mailing list