Your code must load the sql package using the normal method:
package require sql
.
Alternatively you can simply load the shared object using something like:
load ./sql.so
The sql package adds the command
sql
to tcl. This command
takes several subcommands, as listed below. The subcommands
are always the first argument to the
sql
command. The second
argument, if necessary, is the handle for a given connection.
MySQL specific functions are access via the
mysql
command.
Normal usage would be to create a connection via
connect
, select a
database via selectdb
,
query or execute sql commands via
query
and
exec
, close
the query via
endquery
, and
close the connection using
disconnect
.
set conn [sql connect]
set conn2 [sql connect host someuser somepassword]
sql disconnect $conn
sql selectdb $conn mydatabase
sql exec $conn "create table sample (x integer)"
fetchrow
and endquery
. fetchrow
.
sql query $conn "select * from sample where x > 3"
set res_handle [sql query $conn "select * from sample where x > 3"]
sql endquery $conn $res_handle
query
statement.
The row is returned as a tcl list. If there are no more
rows available an empty string is returned.result_handle
parameter is optional; if only one query is issued at a time
it is not necessary.
while {[set row [sql fetchrow $conn]] != ""} { puts $row }
while {[set row [sql fetchrow $conn $res_handle]] != ""} { puts $row }
result_handle
.query
returned the number of rows. It now returns the result handle
(in order to allow multiple queries on the same connection), so
the numrows command was added.
set num_rows_returned [sql numrows $conn $res_handle]
mysql_escape_string()
function.set cmd [mysql escape {Some String}]
# Load the sql package: package require sql # Connect to the database set conn [sql connect] # select the database 'test' to be used. sql selectdb $conn test # Create a table and put some data in it: sql exec $conn "create table junk (i integer, r real, s char(10))" # Put some dummy data in: for {set i 0} {$i < 10} {incr i} { sql exec $conn "insert into junk values ($i, $i.01, 'xx $i xx')" } # Do a select and display the results sql query $conn "select * from junk where i > 3" while {[set row [sql fetchrow $conn]] != ""} { puts "row = $row" } sql endquery $conn sql exec $conn "drop table junk" sql disconnect $connResults:
row = 4 4.0100 {xx 4 xx} row = 5 5.0100 {xx 5 xx} row = 6 6.0100 {xx 6 xx} row = 7 7.0100 {xx 7 xx} row = 8 8.0100 {xx 8 xx} row = 9 9.0100 {xx 9 xx}