Accessing A Database
Revision as of 12:09, 17 January 2012 by Visitatvishal (talk | contribs)
- Note: This tutorial is still very incomplete as of 16aug2004.
This is the simplest example of how to query a database. It is not the recommended way to do it.
<% # set pool "postgres_pool", defined in aolserver.tcl/config.tcl set pool "postgres_pool" set sql "select * from users" set db [ns_db gethandle $pool] set row [ns_db select $db $sql] while {[ns_db getrow $db $row]} { ns_adp_puts "row: [ns_set array $row]" } ns_db releasehandle $db %>
Caveats:
- If you don't explicitly do an [ns_db releasehandle $db], that connection will not be returned to the pool, which can lead to accidentally exhausting all pool handles. This can easily happen if an uncaught Tcl error is thrown in code before the [ns_db releasehandle] call is made, thus causing it to never get executed.
This isn't true. All handles are released after the connection has finished processing. However, you should be aware that a db handle is a precious resource, so before you ns_return the results of your query, which may potentially take a long time, you should release your handles manually.
See also
- ns_db, Introduction to Database Access With nstcl on The Tcler's Wiki (the nstcl package reimplements the ns_* functions from AOLserver)