In my use case, I want to write a function to insert a row in a table in Golang if the row is not available already. I am using MySql and github.com/go-sql-driver/mysql. I am getting an error while I try to insert through this function. But I am able to insert by running through the MySql console. Here is the function definition,
func AddTag(t *objects.Tag) {
//Get connection object
db, err := GetDBConnection()
defer db.Close()
// Prepare statement for inserting data
stmtIns, err := db.Prepare("INSERT INTO tag (tag_id, tag_name, metatag_id) SELECT * FROM (SELECT NULL, ?, ?) AS tmp WHERE NOT EXISTS ( SELECT tag_name FROM tag WHERE tag_name = ? ) LIMIT 1")
if err != nil {
fmt.Println("FATAL ", time.Now(), "Error in prepare statement for Tag insert ")
panic(err.Error())
}
defer stmtIns.Close() // Close the statement when we leave main() / the program terminates
_, err = stmtIns.Exec(t.TagName, t.MetaTagId, t.TagName) // Insert tuples
if err != nil {
fmt.Println("FATAL ", time.Now(), "Error in insert to Tag ")
panic(err.Error())
}
}
Edit 1 : I am getting the following error,
FATAL 2015-06-14 17:13:15.631487042 -0700 PDT Error in insert to Tag
panic: Error 1136: Column count doesn't match value count at row 1
goroutine 1 [running]:
main.AddTag(0x1112e1a0, 0x0, 0x0)
Could anyone help me on this? Thank you
"Column count doesn't match value count" means that you didn't provide a value for a column in the table which doesn't have a default value.
Check your table schema (DESCRIBE tag;
) and ensure that you are providing values for the other columns, or that they have a default value.