mysqltcl(3)
β¨ NAME β¨
mysqltcl(3) β MySQL server access commands for Tcl πΈ
β¨ SYNOPSIS β¨
package require Tcl 8.4
package require mysqltcl 3.0
::mysql::connect ?option value...?
::mysql::use handle database
::mysql::sel handle sql-statement ?-list|-flatlist?
::mysql::fetch handle
::mysql::exec handle sql-statement
::mysql::query handle sql-select-statement
::mysql::endquery query-handle
::mysql::map handle binding-list script
::mysql::receive handle sql-statment binding-list script
::mysql::seek handle row-index
::mysql::col handle table-name option
::mysql::col handle table-name optionkist
::mysql::col handle ?option...?
::mysql::info handle option
::mysql::baseinfo option
::mysql::ping handle
::mysql::changeuser user password ?database?
::mysql::result handle option
::mysql::state handle ?-numeric?
::mysql::close ?handle?
::mysql::insertid handle
::mysql::escape ?handle? string
::mysql::autocommit handle boolean
::mysql::commit handle
::mysql::rollback handle
::mysql::nextresult handle
::mysql::moreresult handle
::mysql::warningcount handle
::mysql::isnull value
::mysql::newnull
::mysql::setserveroption handle option
::mysql::shutdown handle
::mysql::encoding handle ?encoding?
β¨ DESCRIPTION β¨
MySQLTcl is a collection of Tcl commands and a Tcl global array that provide access to MySQL database servers. π
MySQLTcl is nothing more than a patched version of a patched version of Hakan Soderstrom's patch of Tom Poindexter's Sybtcl. No cap, it's patches all the way down π§
Mysqltcl is a binary Tcl library (extension) written in C language that uses the official MySQL C-API directly. Almost all Tcl commands correspond to MySQL C-API functions. For detailed documentation see the official MySQL C-API manual. π
β¨ MYSQLTCL COMMANDS β¨
::mysql::connect ?option value...?
Connect to a MySQL server. A handle is returned which should be used in other mysqltcl commands using this connection. ::mysql::connect raises a Tcl error if the connection fails. ::mysql::connect reads first the options from my.cnf file group mysqltcl. See MySQL documentation chapter "options files". Possible connection options are:
-hosthostname β The host on which the server is located. The local host is used by default. π-useruser β The user whose name is used for the connection. The current Unix user-name is used by default. π€-passwordpassword β The password that must be used for the connection. If it is not present, the connection is possible only for users with no password on the server. π-dbdb β If this option is present,dbis used as current database, with no need for a call tomysql::use. ποΈ-portport β The port number for the TCP/IP connection, if it's different from the default. π-socketsocket β The socket or named pipe for the connection. π§¦-encodingencodingname β The option works similar to-encodingoption infconfigure. It supports also special encoding namebinary. By option-binaryno converting will be done by reading or writing to/from MySQL. If option is not set the system encoding (seeutf-8) is used. Please test all input and outputs with another program to check that all is the way you expect it. If optionbinaryis not used the system proceduresTcl_ExternalToUtfDString(writing) andTcl_ExternalToUtf(reading) will be used; by optionbinarythe functionTcl_GetByteArrayFromObjandTcl_NewByteArrayObjare used. If you want to manipulate binary date use-encoding binary. By handling textes set your special encoding that you want to use in your database. Consider what another system access the database and what encoding they expect. It can useful to use-encoding utf-8. That is standard encoding in some linux distributions and newer systems. π§¬-compressboolean β Use compression protocol. Default isfalse. ποΈ-odbcboolean β The client is an ODBC client. This changesmysqldto be more ODBC-friendly. Default isfalse. π-noschemaboolean β Don't allow thedb_name.tbl_name.col_namesyntax. This is for ODBC. It causes the parser to generate an error if you use that syntax, which is useful for trapping bugs in some ODBC programs. This changesmysqldto be more ODBC-friendly. Default isfalse. π«-multistatementboolean β Tell the server that the client may send multiple-row-queries (separated by;). If this flag is not set, multiple-row-queries are disabled. Default isfalse. π¦-multiresultboolean β Tell the server that the client can handle multiple-result sets from multi-queries or stored procedures. This is automatically set ifCLIENT_MULTI_STATEMENTSis set. π-localfilesboolean β EnableLOAD DATA LOCALhandling. Default isfalse. π-foundrowsboolean β Return the number of found (matched) rows, not the number of affected rows. Default isfalse. π-interactiveboolean β Allowinteractive_timeoutseconds (instead ofwait_timeoutseconds) of inactivity before closing the connection. The client's sessionwait_timeoutvariable will be set to the value of the sessioninteractive_timeoutvariable. Default isfalse. β³-sslboolean β Switch to SSL after handshake. Default isfalse. π-sslkeystring β is the pathname to the key file. Used if-sslis true. π-sslcertstring β is the pathname to the certificate file. Used if-sslis true. π-sslcastring β is the pathname to the certificate authority file. Used if-sslis true. ποΈ-sslcapathstring β is the pathname to a directory that contains trusted SSL CA certificates in pem format. Used if-sslis true. π-sslcipherstring β is a list of allowable ciphers to use for SSL encryption. Used if-sslis true. π-reconnectboolean β default isfalse. π
::mysql::use handle database
Associate a connected handle with a particular database. handle must be a valid handle previously obtained from ::mysql::connect. mysql::use raises a Tcl error if the handle is not valid or if the database name specified could not be used.
Consider you can use mysqltcl without to specify the database, in this case you must use explizit schema notation to specify the table in sql.
::mysql::sel $handle {select * from uni.student}
with option connection -noschema you can prohibit such syntax.
::mysql::sel handle sql-statement ?-list|-flatlist?
Send sql-statement to the server.
If sql-statement is a SELECT statement and no -list or -flatlist option is specified, the command returns the number of rows returned as the result of the query. The rows can be obtained by the ::mysql::fetch and/or the ::mysql::map commands. The resulting rows are called the pending result.
If sql-statement is a SELECT statement and -list or -flatlist is specified, the command returns the full list of rows returned as the result of the query in one of two possible formats:
-listgenerates a list of lists, in which each element is a row of the result.-flatlistgenerates the concatenation of all rows in a single list, which is useful for scanning with a singleforeach.
Example:
% ::mysql::sel $db "SELECT ID, NAME FROM FRIENDS" -list
{1 Joe} {2 Phil} {3 John}
% ::mysql::sel $db "SELECT ID, NAME FROM FRIENDS" -flatlist
{1 Joe 2 Phil 3 John}
Note that both list syntaxes are faster than something like
% ::mysql::sel $db "SELECT ID, NAME FROM FRIENDS"
% ::mysql::map $db {id name} {lappend result $id $name}
% set $result
{1 Joe 2 Phil 3 John}
If sql-statement is a valid MySQL statement, but not a SELECT statement, the command returns -1 after executing the statement, or an empty string if -list or -flatlist is specified. There is no pending result in this case.
In any case ::mysql::sel implicitly cancels any previous result still pending for the handle.
::mysql::fetch handle
Returns the next row from result set as Tcl list. mysql::fetch raises a Tcl error if there is no pending result for handle. mysql::fetch was former named mysqlnext.
::mysql::exec handle sql-statement
Send sql-statement, a MySQL non-SELECT statement, to the server. The handle must be in use (through ::mysql::connect and ::mysql::use).
::mysql::exec implicitly cancels any previous result pending for the handle.
If sql-statement is a valid MySQL SELECT statement, the statement is executed, but the result is discarded. No Tcl error is generated. This amounts to a (potentially costly) no-op. Use the ::mysql::sel command for SELECT statements.
::mysql::exec returns the number of affected rows (DELETE, UPDATE). In case of multiple statement ::mysql::exec returns a list of number of affected rows.
::mysql::query handle sql-select-statement
Send sql-select-statement to the server.
mysql::query allow one to send multiple nested queries on one handle (without need to build new handle or caching results). mysql::query return a query handle that can be used as handle in commands as (mysql::fetch, ::mysql::map, mysql::seek, mysql::col, mysql::result). After result proceeding all query must be freed with ::mysql::endquery query-hanlde command.
Example:
set query1 [::mysql::query $db {SELECT ID, NAME FROM FRIENDS}\]
while {[set row [::mysql::fetch $query1]]!=""} {
set id [lindex $row 0]
set query2 [::mysql::query $db "SELECT ADDRESS FROM ADDRESS WHERE FRIENDID=$ID"]
::mysql::map $query2 address { puts "address = $address" }
::mysql::endquery $query2
}
::mysql::endquery $query1
Okay so like, bestie, in most cases you should use sql-joins and avoid nested queries entirely. The SQL-server can optimize those joined queries, fr fr. But in some applications (GUI-Forms, iykyk) where the results hang around for a long time, the inner query isn't known until you're already deep in it. π
::mysql::endquery query-handle
Free that result memory, bestie β after the ::mysql::query command did its thing. You must invoke ::mysql::endquery after each mysqlquery or you will cause memory leaks. π Like, every single time. See the mysqlquery command for the deets.
Using ::mysql::endquery on a db-handle will also free memory (pending result) after a ::mysql::sel command. π§
::mysql::map handle binding-list script
Iterate a script over the rows of the pending result. β¨ ::mysql::map may consume all the rows or only some of the rows of the pending result. Any remaining rows can still be grabbed by further ::mysql::fetch or ::mysql::map commands. No crumbs left behind unless you want them.
- handle must be a handle with a pending result from a previous
::mysql::selcommand. π«Ά - binding-list must be a list of one or more variable names.
- script must be a Tcl script. It may be empty, but usually it's got one or more commands in it.
::mysql::map processes one row at a time from the pending result. For each row the column values are bound to the variables in the binding list, then the script is executed. Binding is strictly positional. The first variable in the binding list is bound to the first column of the row, and so on. The variables are created in the current context (if they don't already exist). A variable name beginning with a hyphen is not bound; it just serves as a placeholder in the binding list. If there are more columns than variables, the extra columns are ignored. π
The ::mysql::map command is similar to an ordinary foreach. A foreach iterates over the elements of a list; ::mysql::map iterates over the rows of a pending result. In both cases iteration is affected by break and continue Tcl commands. The binding list variables retain their last values after the command has completed. π
A simple example follows. Assume $db is a handle in use. π
::mysql::sel $db {
select lname, fname, area, phone from friends order by lname, fname
}
::mysql::map $db {ln fn - phone} {
if {$phone == {}} continue
puts [format "%16s %-8s %s" $ln $fn $phone]
}
The ::mysql::sel command gets and sorts all rows from table friends. The ::mysql::map command is used to format and print the result in a way suitable for a phone list. π For demonstration purposes one of the columns (area) is not used. The script begins by skipping over rows which have no phone number. The second command in the script formats and prints values from the row. ate and left no crumbs.
::mysql::map raises a Tcl error if there is no pending result for handle, or if binding-list contains more variables than there are columns in the pending result. π
::mysql::receive handle sql-statment binding-list script
This one works the same way as the command mysqtclmap but it does not need a leading ::mysql::sel command. The main difference is the internal using of the MySQL client library. π This command uses mysql_use_result from the C-API, which does not store the result on the client but tries to receive the rows directly from the server. There's also no client cache. This command can be faster than using ::mysql::sel, and with a very big resultset it will not overload the client machine. π
The scipt should process the result immediately because it can block table (or tables) for other clients. β οΈ
If performance matters, please test all alternatives separately. You must consider two aspects: memory consumption and performance. π§
::mysql::seek handle row-index
Moves the current position among the rows in the pending result. β¨ This may cause ::mysql::fetch and ::mysql::map to re-read rows, or to skip over rows. Rewind, fast-forward, whatever the vibe is.
- Row index
0is the position just before the first row in the pending result. π - Row index
1is the position just before the second row, and so on. - You may specify a negative row index. Row index
-1is the position just before the last row; row index-2is the position just before the second last row, and so on. π - An out-of-bounds row index will cause
::mysql::seekto set the new current position either just before the first row (if the index is too negative), or just after the last row (if the index exceeds the number of rows). This is not an error condition. π
::mysql::seek returns the number of rows that can be read sequentially from the new current position. ::mysql::seek raises a Tcl error if there is no pending result for handle. π
Portability note: The functionality of ::mysql::seek is frequently absent in other Tcl extensions for SQL. That's because the MySQL C-API client library offers its own result set caching functionality that other SQL-APIs lack. That increases the performance because all rows are received at once and the query does not block the server for another clients β on the other hand, you're working on cached data, which can use a lot of memory and is up to date only in the moment of query but not fetch. π«
::mysql::col handle table-name option
::mysql::col handle table-name optionkist
::mysql::col handle ?option...?
Return information about the columns of a table. β¨ handle must be in use. table-name must be the name of a table; it may be a table name or -current if there is a pending result. One or more options control what information to return. Each option must be one of the following keywords. π
nameβ Return the name of a column. π·οΈtypeβ Return the type of a column; one of the stringsdecimal,tiny,short,long,float,double,null,timestamp,long long,int24,date,time,date time,year,new date,enum,set,tiny blob,medium blob,long blob,blob,var string, orstring. Note that a column of typecharwill returntiny, while they are represented equally. π€―lengthβ Return the length of a column in bytes. πtableβ Return the name of the table in which this column occurs.non_nullβ Return the string"1"if the column is non-null; otherwise"0".prim_keyβ Return the string"1"if the column is part of the primary key; otherwise"0". πnumericβ Return the string"1"if the column is numeric; otherwise"0".decimalsβ Return the string"1"if the column is non-null; otherwise"0".
The three forms of this command generate their result in a particular way. π«Ά
- If a single option is present the result is a simple list of values; one for each column.
- If the options are given in the form of an option list the result is a list of lists. Each sublist corresponds to a column and contains the information specified by the options.
- If several options are given, but not in a list, the result is also a list of lists. In this case each sublist corresponds to an option and contains one value for each column.
The following is a sample interactive session containing all forms of the ::mysql::col command and their results. The last command uses the -current option. It could alternatively specify the table name explicitly. π
%::mysql::col $db friends name
name lname area phone
% ::mysql::col $db friends {name type length}
{fname char 12} {lname char 20} {area char 5} {phone char 12}
% ::mysql::sel $db {select * from friends}
% ::mysql::col $db -current name type length
{fname lname area phone} {char char char char} {12 20 5 12}]
::mysql::info handle option
Return various database information depending on the option. β¨ The option must be one of the following keywords. π
infoβ Return a String with information about the last operation."Records: 3 Duplicates: 0 Warnings: 0"by INSERT or"Rows matched: 40 Changed: 40 Warnings: 0"by UPDATE statements (read the manual formysql_infoin the MySQL C API documentation). πdatabasesβ Return a list of all database names known to the server. The handle must be connected. πdbnameβ Return the name of the database with which the handle is associated. The handle must be in use.dbname?β Return the name of the database with which the handle is associated; an empty string if the handle is connected, but not in use. π«hostβ Return the name of the host to which the handle is connected. The handle must be connected.hostβ Return the name of the host to which the handle is connected; an empty string if the handle is not valid.tablesβ Return a list of all table names in the database with which the handle is associated. The handle must be in use. ποΈserverversionβ Returns the version number of the server as a string.serverversionidβ Returns the version number of the server as an integer. π’sqlstateβ Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters.'00000'means "no error." The values are specified by ANSI SQL and ODBC. Note that not all MySQL errors are yet mapped to SQLSTATE's. The value'HY000'(general error) is used for unmapped errors. π¨stateβ Returns a character string containing information similar to that provided by themysqladmin statuscommand. This includes uptime in seconds and the number of running threads, questions, reloads, and open tables. π::mysql::baseinfo optionβ hands you the lil info bits that don't need a handle to fetch. no handle required, bestie, it's that easy β¨connectparametersβ returns all supported connecting optionsclientversionβ returns the version of the underlying MYSQL C-API library
::mysql::ping handleβ checks whether the connection to the server is still working. And if it's gone down? An automatic reconnection is attempted. self-healing era fr π«Ά
This one's for the clients that just sit there idle for a long while β it lets you check whether the server has closed the connection and reconnect if necessary.
Returns True if the server is alive. π
::mysql::changeuser user password ?database?β changes the user, and makes the database named by database become the default (current) database on the connection. In subsequent queries, that database is the default for table references that don't include an explicit database specifier. switch it up, iconically π¦
::mysql::changeuser fails unless the connected user can be authenticated, or if they don't have permission to use the database. In that case, the user and database are not changed β nothing happens, no cap.
If database parameter may be set were is no default database.
Causes an Error if the operation is not succesed. π
::mysql::result handle optionβ returns information about the pending result. Heads up: a result stays pending until it's canceled by a::mysql::execcommand, even if no rows remain to be read. option must be one of these keywords:colsβ return the number of columns in the pending result. There must be a pending result.colsβ return the number of columns in the pending result; an empty string if no result is pending.currentβ return the current position in the pending result; a non-negative integer. This value can be used as a row-index in the::mysql::seekcommand. An error is raised if there is no pending result.current?β as above, but returns an empty string if there is no pending result. the chill version, she doesn't yellrowsβ return the number of rows that can be read sequentially from the current position in the pending result. There must be a pending result.rowsβ return the number of rows that can be read sequentially from the current position in the pending result; an empty string if no result is pending.
And the math? [::mysql::result $db current] + [::mysql::result $db rows] always equals the total number of rows in the pending result. slay, consistent β¨
::mysql::state handle ?-numeric?β returns the state of a handle as a string, or in numeric form. There is no requirement on handle; it may be any string. The return value is one of the following strings, or the corresponding numeric value if-numericis specified. The states form a progression where each state builds on the previous one. character development arc, honestly πNOT_A_HANDLE(0) β the string supplied for handle is not a mysqltcl handle at all.UNCONNECTED(1) β the string supplied for handle is one of the possible mysqltcl handles, but it is not valid to any server.CONNECTED(2) β the handle is connected to a server, but not associated with a database.IN_USE(3) β the handle is connected and associated with a database, but there is no pending result.RESULT_PENDING(4) β the handle is connected, associated with a database, and there is a pending result. π
::mysql::close ?handle?β closes the server connection associated with handle, sending it back to the unconnected state. Closes all connections if handle is omitted. Returns an empty string.::mysql::closeraises a Tcl error if a handle is specified which is not valid. π::mysql::insertid handleβ returns the auto increment id of the lastINSERTstatement. π::mysql::escape ?handle? stringβ returns the content of string, with all special characters escaped, so it's suitable for use in an SQL statement. This is simpler (faster) than using a general regexp or string map. If handle is specified, the C-API functionmysql_real_escape_stringis used. And that's the recommended usage β because in that case the current character set is respected. π::mysql::autocommit handle booleanβ sets autocommit mode on if mode is 1, off if mode is 0.::mysql::commit handleβ commits the current transaction. β¨::mysql::rollback handleβ rollback the current transaction. we love an undo button::mysql::nextresult handleβ if more query results exist,mysql::nextresult()reads the next query results and returns the status back to the application. Returns -1 if no result, or the number of rows in the result set.::mysql::moreresult handleβ returns true if more results exist from the currently executed query, and the application must callmysql::resultto fetch the results. π¦::mysql::warningcount handleβ returns the number of warnings generated during execution of the previous SQL statement. the receipts, bestie::mysql::isnull valueβ okay so null handling is a known problem with Tcl, especially with DB interaction. Here's the tea: the mysql"varchar"type has two valid blank values,NULLand an empty string. That's where the problem arises β Tcl is not able to differentiate between the two because of the way it handles strings. literally the whole issue π
Mysql has a new internal Tcl type for null, whose string representation is stored in the global array mysqltcl(nullvalue), and as default an empty string. mysql::isnull can be used for a safe check for null value.
Warning: mysql::isnull works only reliable if there are no type conversation on returned rows. Consider a row is always a Tcl list even when there are only one column in the row. π
set row [::mysql::next $handle]
if {[mysql::isnull [lindex $row 1]]} {
puts "2. column of $row is null"
}
if {[mysql::isnull $row]} {
puts "this does not work, because of type conversation list to string"
}
see how the second one just does not work? that's the type conversation biting you, not me π
::mysql::newnullβ create new null object. It can be used to simulate returned row contents. π::mysql::setserveroption handle optionβ there are only 2 options now:-multi_statment_onand-multi_statment_off.::mysql::shutdown handleβ asks the database server to shut down. The connected user must have SHUTDOWN privileges. you're the main character now, use it wisely π::mysql::encoding handle ?encoding?β ask or change a encoding of connection. There are special encoding"binary"for binary data transfers. β¨
πΈ STATUS INFORMATION πΈ
Mysqltcl creates and maintains a Tcl global array to provide status information. Its name is mysqlstatus. π
Mysqlstatus elements:
codeβ a numeric conflict code set after every mysqltcl command. Zero means no conflict; non-zero means some kind of conflict. All conflicts also generate a Tcl error.
All MySQL server conflicts set mysqlstatus(code) to the numeric code of the MySQL error.
Any other conflict sets mysqlstatus(code) to -1.
commandβ the last failing mysqltcl command. Not updated for successful commands.messageβ message string for the last conflict detected. The same string is returned as the result of the failing mysqltcl command. Not updated for successful commands.nullvalueβ the string to use in query results to represent the SQL null value. The empty string is used initially. You may set it to another value. π
π« Backward compatibility π«
Up from version 3.0 all mysql commands are declared in the ::mysql namespace. All names, for example mysqlconnect, are also available but deprecated. All old commands have the name pattern mysql{name} and the most of them are now mysql::{name}. The exception is mysqlnext, which was renamed to mysql::fetch. glow-up era, we simply moved on π¦
π BUGS & POSSIBLE MISFEATURES π
Deleting any of the mysqltcl commands closes all connections. all of them. every single one. not a vibe, but forewarned is forearmed π
π AUTHORS π
- Tobias Ritzau
- Paolo Brutti
- Artur Trzewik (mail@xdobry.de) - active maintainer
MySQLTcl is derived from a patch of msql by Hakan Soderstrom, Soderstrom Programvaruverkstad, S-12242 Enskede, Sweden. msql is derived from Sybtcl by Tom Poindexter. There are many contributors and bug reporter that are not mentioned. If you have contributed to mysqltcl and wants to be on the list contact Artur Trzewik. π
and that's a wrap on mysqltcl(3), version 3.0, bestie β tysm for reading the whole thing, you're literally the main character of your own terminal, now go forth and query responsibly πβ¨π
π¦ where this page comes from
- debian bookworm: mysqltcl 3.052-4
- debian trixie: mysqltcl 3.052-4+b2
- ubuntu noble: mysqltcl 3.052-4ubuntu1
- ubuntu questing: mysqltcl 3.052-4ubuntu2
- ubuntu resolute: mysqltcl 3.052-4ubuntu3
- ubuntu stonking: mysqltcl 3.052-4ubuntu3
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms