Difference between revisions of "Accessing A Database"

From AOLserver Wiki
Jump to navigation Jump to search
m (formatting tweaks)
 
Line 6: Line 6:
  
 
<pre>
 
<pre>
    <%
+
  <%
      # change "poolname" to match the pool you defined in your config.tcl
+
  # set pool "postgres_pool", defined in aolserver.tcl/config.tcl
      set pool "poolname"
+
  set pool "postgres_pool"  
      # change to reflect the SQL you wish to execute
+
  set sql "select * from users"
      set sql "SELECT NOW()"
+
  set db [ns_db gethandle $pool]
 
+
  set row [ns_db select $db $sql]
      set db ""
+
  while {[ns_db getrow $db $row]} {
      catch {
+
    ns_adp_puts "row: [ns_set array $row]"
        set db [ns_db gethandle $pool]
+
  }
        set row [ns_db select $db $sql]
+
  ns_db releasehandle $db
        while {[ns_db getrow $db $row]} {
+
%>
          ns_adp_puts "row: [ns_set array $row]<br/>"
 
        }
 
      }
 
      catch { ns_db releasehandle $db }
 
    %>
 
 
</pre>
 
</pre>
  

Latest revision as of 12:09, 17 January 2012

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)