These days you can hardly code anything without it connecting to a database for some reason. A project I made needed to be able to connect to MySQL using TCL – and after some searching I found the brilliant library mysqltcl. It gives you all you need to get TCL to interract with a MySQL database. Below I’ve put together a small example on how to use TCL to do SELECT and INSERT statements as well as how to execute a PROCEDURE.

Code

#**************************************************************
# Title   		: MySQL/TCL Example
# Author  		: Kjell Arne Brudvik (kjell.arne@brudvik.org)
#**************************************************************
 
package require mysqltcl
 
set info(title) "MySQL/TCL Example"
set info(author) "Kjell Arne Brudvik"
set info(version) "1.0"
 
set mysql_db(hostname) ""
set mysql_db(port) ""
set mysql_db(username) ""
set mysql_db(password) ""
set mysql_db(database) ""
set mysql_db(connection) [mysqlconnect -host $mysql_db(hostname) -user $mysql_db(username) -password $mysql_db(password) -port $mysql_db(port) -db $mysql_db(database) -multiresult true]
set mysql_db(db_use) [mysqluse $mysql_db(connection) $mysql_db(database)]
 
bind pub 	- 	!users 		getUsers
bind pub	-	!adduser	createUser
bind pub	-	!execute	executeProcedure
 
proc getUsers { nick host hand chan text } {
	global info mysql_db
	set sql "SELECT * FROM USERS"
	set rs [mysqlquery $mysql_db(connection) $sql]
	set found 0
	while {[set row [mysqlnext $rs]] != ""} {
		set username [lindex $row 0]
		set password [lindex $row 1]
		incr found 1
	}
	set status [mysqlendquery $mysql_db(connection)]
}
 
proc createUser { nick host hand chan text } {
	global info mysql_db
	set arguments [split $text " "]
	set username [lindex $arguments 0]
	set password [lindex $arguments 1]
	set sql "INSERT INTO USERS (USERNAME, PASSWORD) VALUES ('$username', '$password')"
	set rs [mysqlquery $mysql_db(connection) $sql]
	set status [mysqlendquery $mysql_db(connection)]
}
 
proc executeProcedure { nick host hand chan text } {
	global info mysql_db
	set arguments [split $text " "]
	set username [lindex $arguments 0]
	set sql "CALL notify_user('$username')"
	set rs [mysqlexec $mysql_db(connection) $sql]
}
Donate using PayPal
If you found this publication useful to you, then feel free to show your appreaciation towards open-source publications by doing a small donation. It only takes a moment of your time. Any donation is appreaciated – and would also motivate me to release more as open-source. Donations so far – $0 USD – See previous donations.