[Tutor] gdbm / python howto or tutorial

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Aug 18 15:01:09 EDT 2003



On Mon, 18 Aug 2003, Justin Heath wrote:

> I am looking for information on using gdbm with python. I have not used
> gdbm in the past but am interested in using it in cases where I cannot
> use mysql. Therefore, I do need something pretty introductory. I have
> looked for documentation but mostly what I have found is C code, and
> don't want to "learn" C just to get started. Any pointers would be
> appreciated.

Hi Justin,


The documenation to gdbm:

    http://www.python.org/doc/lib/module-gdbm.html

doesn't itself have an example, but it say that 'gdbm' objects behave a
lot like dictionaries (except that keys and values are forced to be
strings).


Here's a quicky example: Let's say that we'd like to create a new DBM
file:

###
>>> import gdbm
>>> definitions = gdbm.open('test_gdbm.dbm', 'c')
>>> definitions['pair programming'] = '''
... An XP practice requiring that each piece of source code
... to be integrated into the software product should be created
... by two programmers jointly at one computer.'''.strip()
>>> definitions['code smell'] = '''
... The unpleasant feeling you get when you see bad code'''.strip()
>>> definitions.close()
###


This saves a 'dbm' file onto disk.  Another program can then open this dbm
file up:

###
>>> import gdbm
>>> definitions = gdbm.open('test_gdbm.dbm')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
gdbm.error: Flag ' ' is not supported.
###


Oh.  Unlike regular file opening, this one doesn't default to 'read' mode,
so we'll have to directly specify it:

###
>>> definitions = gdbm.open('test_gdbm.dbm', 'r')
>>> definitions.keys()
['code smell', 'pair programming']
>>> definitions['code smell']
'The unpleasant feeling you get when you see bad code'
###


Ok, better.  *grin*




By the way, Bob Gailer recently mentioned Sqlite,

    http://www.hwaci.com/sw/sqlite/


which does appear to be an alternative way of getting very lightweight SQL
behavior.  The equivalent code, using Sqlite, looks like:

###
>>> import sqlite
>>> conn = sqlite.connect(db='definitions')
>>> cursor = conn.cursor()
>>> cursor.execute("""create table definitions
...  (word varchar not null, defn varchar not null)""")
>>> cursor.execute("insert into definitions values ('hello', 'world')")
>>> cursor.execute("select * from definitions")
>>> cursor.fetchall()
[('hello', 'world')]
>>> conn.commit()
###

One warning: when using any SQL database, don't forget to commit.  I made
this mistake a couple of times since MySQL has autocommit behavior, and I
still bungle it sometimes... *grin* But the changes to a Sqlite database
won't persist and will be rolled back when we quit the program, unless we
explicitely do the commit().


Hope this helps!




More information about the Tutor mailing list