Python 2.5 and Generic Database Connection Utilities
Python 2.5 has been released today. Yay. I look forward to utilising some of its fine language features in my future code.
But, and you knew there was a gripe coming didn’t you? With the inclusion of the pysqlite module as part of the standard distribution there is a problem. It has been renamed from pysqlite2 to sqlite3. A move I agree with by the way, as it is clear from the name exactly what the module supports.
The problem is I’ve got quite a bit of code that uses the old name. Where my existing scripts say;
>>> from pysqlite2 import dbapi2 as sqlite
They now need to say;
>>> try:
... from pysqlite2 import dbapi2 as sqlite
... except ImportError: # for Python 2.5 and above
... from sqlite3 import dbapi2 as sqlite
>>> myDb = sqlite.connect('sqlitedatabasefile.db')
Or they would, if I hadn’t cunningly stolen an idea from SQLObject, which they borrowed from any number of other places, and written my own little connection function. So my scripts can carry on using;
>>> from utilities.dburi import get_connection
>>> myDb = get_connection('sqlite:/sqlitedatabasefile.db')
Fancy a look at the code? Oh, ok then, it’s called dburi.py and there is a text version of the file called dburi.py.txt. Patches are gratefully accepted.
Lightning talk
Comment by Richard Jones — September 20, 2006 @ 7:05 pm
I do:
try:
import sqlite3 # Python 2.5 and up
except ImportError:
from pysqlite2 import dbapi2 as sqlite3
in similar ‘central’ db access code (I create a connection wrapper that inits the tables if needed, and adds convenience methods and abstractions). See:
http://svn.plone.org/view/collective/linktally/trunk/src/linktally/db.py?rev=25691&view=auto
Comment by Martijn Pieters — September 20, 2006 @ 10:18 pm
Standard library!
(well, something similar should be added to the standard library, at least. where the “schema” part is used to locate the driver, and driver-specific code handles the rest of the “uri”)
Comment by Fredrik — September 20, 2006 @ 11:03 pm
Personally, I’d be quite interested in seeing all the database systems converge on one format and loading mechanism, maybe a common package implementing it. Maybe discuss on DB-SIG?
Comment by Ian Bicking — September 21, 2006 @ 3:55 am
Neat.
Comment by Alan Green — September 21, 2006 @ 6:24 am