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.
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...
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:
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.db = ns_db() if db.select('SELECT id FROM sometable'): while db.nextrow(): print "id %s" % db['id']
ns_db.dbhandle
is the database handle string,
and ns_db.selection
is the database selection
result, and they can be passed directly into the 'ns_db'
routines via the Tcl namespace dictionary. If you do this
without understanding the Python code that manages them, you'll
probably get odd results.
Despite the pretty interface, the evil of ns_db lurks in the bowels of the code - so, no nested or simultaneous queries, in particular! One query per one handle at a time.
invalidate()
- flushes the results, drops the
handle
is_valid()
- are we on a valid row?
select(query)
, only1row(query)
,
only0or1row(query)
- run queries.
nextrow()
- fill the dictionary in with the values
from the next row.
In addition, all of the usual (read-only) namespace functions work correctly.
And that's pretty much it.
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
For example, instead of the Tcl command
do, in Python,set db [ns_db gethandle main] set connected [ ns_db connected $db ]
db = ns_db("main") connected = db.connected()
#! /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'])