K
K
Kagtaviy2016-06-09 17:30:40
MySQL
Kagtaviy, 2016-06-09 17:30:40

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)
}

Then I do this:
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)
}

My logic is something like this. I'm doing a lookup on the user_Id column in the users table with the userId data I got earlier. If there are no matches, then I need to execute, for example, fmt.Println("No matches found"). Can you please tell me how to check for matches and then call Println?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
ThunderCat, 2016-06-09
@ThunderCat

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)
    }

This is from the official manual.

A
Alexander Semchenko, 2016-06-11
@0xcffaedfe

_ "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
}

I use like this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question