[DB-SIG] perl-DBI like module for Python?

Kevin Jacobs jacobs at theopalgroup.com
Wed May 26 08:32:00 EDT 2004

Stuart Bishop wrote:

> On 24/05/2004, at 4:57 PM, Mihai Ibanescu wrote:
>> Example: I have my application running against Postgres. I have to be 
>> able to
>> port it to Oracle too. Unfortunately, code that tries to catch
>> DatabaseException will have to look for the cx_Oracle 
>> DatabaseException, not
>> for the postgres one.
> The exceptions are most likely exposed through your connection object
> (I think most the major drivers support this option now?).
> try:
>     cur = con.cursor()
>     cur.excecute('select foo from bar')
> except con.DatabaseException:
>     print 'Oops!'
A more portable way is to use my exception virtualization technique
that allows the use of a standard set of exceptions to catch
exceptions generated from registered db-api modules:

dbapi_exceptions = [ 'Warning',
                     'NotSupportedError' ]

class Warning               (StandardError)     : pass
class Error                 (StandardError)     : pass
class   InterfaceError        (Error)           : pass
class   DatabaseError         (Error)           : pass
class     DataError             (DatabaseError) : pass
class     OperationalError      (DatabaseError) : pass
class     IntegrityError        (DatabaseError) : pass
class     InternalError         (DatabaseError) : pass
class     ProgrammingError      (DatabaseError) : pass
class     NotSupportedError     (DatabaseError) : pass

def __import_exceptions(module):
  for e in dbapi_exceptions:
    sub_exception    = getattr(module, e)
    global_exception = globals()[e]
    if global_exception not in sub_exception.__bases__:
      sub_exception.__bases__ += (global_exception,)

One can then "register" a db-api module to allow exceptions to be caught
from the above virtual exceptions:

import psycopg
import popy
import mysqldb



More information about the DB-SIG mailing list