How do you solve the problem with mysql golang?
-
Hello, I've been struggling with this. I'm on Mysql base.
db, err := sql.Open("mysql", "user:password@/") defer db.Close() if err != nil { panic(err) }
Then I want to check on the matches in the database, I'll do the code:
key := 1545 var user_key string err = db.QueryRow("SELECT * FROM users WHERE user_key=?", key).Scan(&user_key) switch { case err == sql.ErrNoRows: log.Printf("No user with that key.") case err != nil: log.Fatal(err) default: fmt.Println("User key, ", user_key) }
Table mysql:
CREATE TABLE `users` ( `user_id` INT(10) NOT NULL AUTO_INCREMENT, `user_key` INT(11) NULL DEFAULT '0', `user_login` VARCHAR(35) NULL DEFAULT '0', PRIMARY KEY (`user_id`) )
That's what makes the log:
2016/06/10 10:17:54 sql: expected 3 destination arguments in Scan, not 1
Tell me how to solve the problem, the google goes on and on and off.
-
Why Google when there's godoc.org? Conduct https://godoc.org/database/sql#Row.Scan similar to conduct https://godoc.org/database/sql#Rows.Scan ♪ And in fact:
The number of values in dest must be the same as the number of columns in Rows.
Which means that the number of arguments should be equal to the number of columns in the table. In other words
var userId int var userKey int var userLogin string err = db.QueryRow("SELECT * FROM users WHERE user_key=?", key). Scan(&userId, &userKey, &userLogin)
Or
var userKey int err = db.QueryRow("SELECT users.user_key FROM users WHERE user_key=?", key). Scan(&userKey)