DB beginner help
David Cook
davecook at nowhere.net
Thu Aug 5 06:12:06 EDT 2004
On 2004-08-05, Zeljko Vrba <mordor at fly.srk.fer.hr> wrote:
> 2. How are you supposed to write DB-driver independent code when each
> driver has its own, possibly different from any other, paramstyle
> ('qmark', 'numeric', etc..)?
This recipe might help:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278612
I haven't tried it.
> In Perl I always use question marks and have no trouble switching the
> application between different databases. How do you guys do it in Python
> (of course, without rewriting all queries?)
pyformat is the most useful IMO, e.g.
cursor.execute(
"insert into foo (baz, quux) values (%(baz)s, %(quux)s)",
{'parrot' : 'deceased', 'quux' : "O'Reilly", 'baz' : 1})
The values for 'baz' and 'quux' will be interpolated and quoted correctly,
and 'parrot' will be ignored.
A few adapters have a dictfetch method, but for those that don't, getting
your data out in dict form is a two liner:
fieldnames = [tup[0] for tup in cursor.description]
dictrows = [dict(zip(fieldnames, row)) for row in cursor.fetchall()]
Dave Cook
More information about the Python-list
mailing list