The ns_db routines and their Python API

Warning!

The ns_db module is based on the old Tcl interface. It is obsolete and deprecated. For new applications, it is suggested that you use the database interface that is part of the AOLserver Python API. We may in the future provide a higher-level database interface based on the Python API but it probably won't look much like this one.

You have been warned!

Nomenclature: ns_db refers to the Tcl function 'ns_db' internal to AOLserver. ns_db() refers to the Python class that is in ns_python.py.

99% of readers can read the first two sections (describing the Python wrapper functions) and ignore the rest, which describes the (few, rarely used) commands that have been left out or superceded.

But first, show me an example Python script...


ns_db functions wrapped loosely

All of these can be used pretty much without thought through the ns_db() interface; just don't pass the handle to anything except the ns_db() constructor. [Example]

ns_db() -- heavily Python-specific functionality

In an effort to take advantage of the features of Python objects, some of the ns_db functions have been wrapped into an object structure. An effort has been made to keep it intuitive ;).

There's one main principle to remember:

ns_db() instances are (primarily) objects that act as dictionaries for 'select' results

A quick example, before we move on to discuss some of the intricacies:

db = ns_db()
if db.select('SELECT id FROM sometable'):
   while db.nextrow():
      print "id %s" % db['id']
As you can see, the interface is pretty much the same as the Tcl interface, at least in terms of what we're doing: running a query and iterating through the results.

What not to do:

What are the new functions, and what parameters do they take?

In addition, all of the usual (read-only) namespace functions work correctly.

And that's pretty much it.


ns_db functions that have been superceded by ns_db() calls:

There may be similar sounding functions (select) or slightly modified functions (1row has become only1row), but in general the use of these functions through e.g. the Tcl namespace will screw up ns_db() functionality

Functions that have no place in a sane ns_db module:


Using the loosely wrapped functions:

For example, instead of the Tcl command

set db [ns_db gethandle main]
set connected [ ns_db connected $db ]
do, in Python,
db = ns_db("main")
connected = db.connected()

A full example script.

This script returns a simple listing of the database table 'bac_ends'.
#! /usr/bin/python
from ns_python import *

ns_tcl.ReturnHeaders()

db = ns_db()

if db.select('SELECT id,name FROM bac_ends'):
    while db.nextrow():
        print "id %s, name %s.<p>" % (db['id'], db['name'])