#This code prints out all products in the database
# that are below a specified price (assumed to have been determined
# beforehand, and stored in the variable targetPrice)
# The output is in HTML table format, appropriate for CGI output
#load the SQL shared object library. the Tcl interpreter could also
#have been compiled with the library, making this line unnecessary
load /home/aroetter/tcl-sql/sql.so
#these are well defined beforehand, or they could
#be passed into the script
set DBNAME "clientWebSite";
set TBLNAME "products";
set DBHOST "backend.company.com"
set DBUSER "mysqluser"
set DBPASSWD "abigsecret"
set targetPrice 200;
#connect to the database
set handle [sql connect $DBHOST $DBUSER $DBPASSWD]
sql selectdb $handle $DBNAME ;# get test database
#run a query using the specified sql code
sql query $handle "select * from $TBLNAME where price <= $targetPrice"
#print out html table header
puts "<table border=4>"
puts "<th>Product Id <th width=200>Description <th>Price (\$)"
#output table rows - each fetchrow retrieves one result
#from the sql query
while {[set row [sql fetchrow $handle]] != ""} {
set prodid [lindex $row 0]
set descrip [lindex $row 1]
set price [lindex $row 2]
puts "<tr><td>$prodid <td align=center>$descrip <td>$price"
}
puts "</table>"
#empty the query result buffer - should already be empty in this case
sql endquery $handle
#close the db connection - in practice this same connection
#is used for multiple queries
sql disconnect $handle
|