Search code examples
databasetcltdbc

TCL tdbc command line arguments


I am trying to connect to a database with command line arguments but I am getting invalid command name "2" while executing "2"

I have searched quite a bit and cannot find any solution...here is my code

package require tdbc::mysql

tdbc::mysql::connection create db1 -database $argv[2] -user $argv[3] -password $argv[4]

db1 allrows {create table Grades (TNumber char(8), CourseID char(7), Grade char(1, foreign key(TNumber) references Students(TNumber))}

set s [db prepare 
{
INSERT into Grades values (00003256,CSC4300,A)
}] 
set s [db prepare 
{
INSERT into Grades values (00012345,CSC2110,D)
}] 
set s [db prepare 
{
INSERT into Grades values (00012345,CSC2110,D)
}] 
set s [db prepare 
{
INSERT into Grades values (00001423,BIO1010,D)
}] 
set s [db prepare 
{
INSERT into Grades values (00015366,CSC2110,C)
}] 
set s [db prepare 
{
INSERT into Grades values (00003256,CSC4100,A)
}] 
set s [db prepare 
{
INSERT into Grades values (00003256,CSC2110,A)
}] 


db1 close

EDIT:

I am getting an error when trying to run my revised code at the first db allrows line:

if{[catch {
package require tdbc::mysql
tdbc::mysql::connection create db -user [lindex $argv 2] -db [lindex $argv 1] -password [lindex $argv 3]

db allrows {create table Grades (TNumber char(8), CourseID char(7), Grade char(1, foreign key(TNumber) references Students(TNumber))}

db allrows {db prepare {INSERT into Grades values ('00003256','CSC4300','A')}}


    mysqlclose $s
} res]} {
puts $res
}

here's the error:

coursework@coursework:~/Desktop$ tclsh p4.tcl localhost students root coursework
invalid command name "if{1}"
    while executing
"if{[catch {
package require tdbc::mysql
tdbc::mysql::connection create db -user [lindex $argv 2] -db [lindex $argv 1] -password [lindex $argv 3]

db a..."
    (file "p4.tcl" line 1)

I don't really know tcl, this is just a one time project in a crammed situation! Thanks for all the help!


Solution

  • argv isn't an array (and the square brackets are the wrong syntax for accessing a key in an array anyway - it would be parens). The error message is that it is encountering $argv[2] and first trying to evaluate the command [2] in the second line and failing.

    argv is a list. So, you can do something like:

    foreach name [list nothing1 nothing2 db user pass] val $argv {
      set $name $val
    }
    connection create db1 -database $db -user $user -password $pass 
    

    or just index the argument list:

    connection create db1 -database [lindex $argv 2] -user [lindex $argv 3] -password [lindex $argv 4]
    

    Hard to tell since you didn't specify how it is actually invoked if you have the indexing right, so the number of nothing's in the first example, or the indices in the second may or may not be correct.