Ns dbquery
Jump to navigation
Jump to search
# # ns_dbquery -- # # Execute a SQL query against either a pool or an opened db handle, # and return the resultset as a list of lists. The first list # contains the column names. # # If the statement was a statement which does not return rows, the # result is an empty list. TODO: Perhaps return the number of rows # updated? # proc ns_dbquery {args} { if {([llength $args] - 1) % 2 != 0} { error "wrong # args: should be \"ns_dbquery ?-pool name\ | -handle dbId? ?-timeout secs? sql\"" } foreach {key value} [lrange $args 0 end-1] { switch -exact -- $key { -pool { set pool $value } -handle { set handle $value } -timeout { set timeout $value } } } if {![info exists timeout]} { set timeout 0 } if {[info exists pool]} { set db [ns_db gethandle -timeout $timeout $pool] } elseif {[info exists handle]} { set db $handle } else { # Use default pool, if configured. set db [ns_db gethandle -timeout $timeout] } if {![string length $db]} { error "couldn't get db handle" } set res [catch { set resultset [list] if {[ns_db exec $db [lindex $args end]] eq "NS_ROWS"} { set row [ns_db bindrow $db] set columns [list] foreach {key value} [ns_set array $row] { lappend columns $key } lappend resultset $columns while {[ns_db getrow $db $row]} { set data [list] foreach {key value} [ns_set array $row] { lappend data $value } lappend resultset $data } ns_set free $row } } err] if {![info exists handle]} { ns_db releasehandle $db } if {$res} { error $err } return $resultset }