stupid Python/database connection

Alex Martelli aleax at aleax.it
Mon Nov 25 12:32:59 EST 2002


animeshk wrote:

> This is a really stupid question, I know.
> 
> I am trying to write an app that might connect to an Interbase
> database or an Oracle database, depending on a configuration file.
> 
> I have seen some Python code for interfacing with a database, and it
> seems to depend on the import statement.  import some-lib-or-another
> to access one kind of database, import some-other-lib-or-another to
> access another kind of database.  After the import, it's a matter of
> calling that database type's "connect" statement.
> 
> So . . . how can the decision of what-database-to-use be defferred to
> runtime?  When writing, say, a BDE app in Delphi, it would be a simple
> matter of what alias to use.  How is this done in Python?

The general Pythonic way to do that would be, e.g.:

# read the config file and find out what DB to use
# setting e.g. variable kindofdb appropriately

if kindofdb == 'interbase':
    import interbaseinterfacemodule as dbmodule
    connection = dbmodule.connect("whatever goes here")
elif kindofdb == 'oracle'
    import oracleinterfacemodule as dbmodule
    connection = dbmodule.connect("whatever else goes here instead")
else:
    raise RuntimeError, "Don't know how to connect to DB kind %r" % kindofdb


In this case, you may want to wrap things better than this, since
differences in SQL dialects and so on do most often need to be smoothed
away (sigh).  But if conditional import and connect calls are all
you want, that's one way you can get them.


Alex




More information about the Python-list mailing list