Example code for anydbm wanted...

Alex Martelli aleax at aleax.it
Mon Aug 4 03:18:50 EDT 2003


<posted & mailed>

John D. wrote:

> Does anyone have any good example code that shows how to use the "anydbm"
> wrapper tp interface with a very simple database.   like some examples of
> how to use "dumbdbm"?   Then perhaps at a later time,  I'm going to want
> to then interface it to a more robust database like PostGreSQL or mySQL.  
> But I want to external interface to "hide" the specifics and have a really
> generic interface.
> 
> I already played with Python's interface with PostGreSQL,  but they don't
> follow the generic Python models.  At least my prev version didn't.

I know of no Python interface to any SQL-based RDBMS that mimics the
simplistic interface of anydbm and its underlying modules -- rather,
Python's interfaces to SQL databases normally follow the "DB API" specs.

If you will eventually want to migrate to PostGreSQL, SAP/DB, or the
like, you're therefore better off starting right now with an SQL based
interface rather than anydbm.  Luckily, you have at least two choices
for lightweight SQL based interfaces -- gadfly (which has a pure Python
implementation, though you may speed it up by using some C-coded
extension modules) and PySQlite, which directly interfaces to the
lightweight, C-coded SQlite library for embedding SQL databases in
any program.  I suspect PySQlite is likely to be more suitable for your
purposes (gadfly can have slow startup times, unless you keep it running
in the background as another server process).

Even if you do choose to use DB API compliant modules exclusively,
starting, say, with PySQlite, you're most likely still better off
encapsulating database access within a "database independence layer"
module rather than strewing it around your program.  SQL dialects
accepted by different database engines have small but annoying quirks
(I recommend O'Reilly's "SQL in a Nutshell" for a concise and useful
review of some such issues) and DB API modules may add a few more
points of divergence (such as the choice of %, ?, or others yet, for
value-placeholders in SQL query strings).  By encapsulating all of
your DB accesses into one module, you keep such divergence under far
better control than by strewing them around.  Of course, like in any
portability situation, it's unlikely that your code will actually BE
portable unless you keep trying it out during development on at least
two different platforms -- otherwise, it's all too easy to fall into
some dependence on a specific plaftorm without realizing the fact.  If
you DO develop your code so that it runs against two or more separate
DB API implementations, then if and when you need to add even more
such implementations in the future your task will be manageable and
with any luck actually pretty easy.


Alex





More information about the Python-list mailing list