Accessing A Database

From AOLserver Wiki
Revision as of 05:36, 7 September 2005 by WikiSysop (talk | contribs) (imported from WiKit id 825)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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.

   <%
     # change "poolname" to match the pool you defined in your config.tcl
     set pool "poolname"
     # change to reflect the SQL you wish to execute
     set sql "SELECT NOW()"
     set db ""
     catch {
       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
" } } catch { 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)

Category Documentation - Category Tutorial