Answer the question
In order to leave comments, you need to log in
How to properly process the response?
Hello.
There is a request to MySQL:
rows, err := db.Query("SELECT * FROM users WHERE user_Id=?", userId)
if err != nil {
panic(err)
}
for rows.Next() {
var user_Id string
if err := rows.Scan(&user_Id); err != nil {
log.Fatal(err)
}
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
Answer the question
In order to leave comments, you need to log in
In general, I see the code for the first time, but it seems to me that there is some kind of crap here.
What do you need? understand whether there were matches in the database? So if something got into rows (in the sense the query did not return an empty set), then there are matches in the database, otherwise we write no matches found.
UPD:
In your case, this is more suitable:
id := 123
var username string
err := db.QueryRow("SELECT username FROM users WHERE id=?", id).Scan(&username)
switch {
case err == sql.ErrNoRows:
log.Printf("No user with that ID.")
case err != nil:
log.Fatal(err)
default:
fmt.Printf("Username is %s\n", username)
}
_ "github.com/go-sql-driver/mysql"
import "github.com/jinzhu/gorm"
type User struct {
id int `json:"id"`
name string `json:"name"`
/*
Some crap here....
*/
}
func GetUsersById(id int) (user *User, err error) {
user = &User{}
if err = DB.Table("users").Where("id = ?", id).First(&user).Error; err != nil {
return user, err
}
return user, err
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question