QueryRow().Scan() 如果行不存在,则返回错误。

huangapple go评论141阅读模式
英文:

QueryRow().Scan() returns error if row doesn't exist

问题

我想从 SQL 数据库中获取一行数据。我使用以下代码:

var name string
row := db.Con().QueryRow("SELECT name FROM users WHERE id = 2;")
err := row.Scan(&name)

if err != nil {
    // 记录错误日志
}

例如:如果 id=2 的用户不存在,那么 Scan 方法会返回一个错误。

问题:

有没有办法在行不存在时避免这个错误?因为这是完全正常的情况,我不想记录这样的错误。

我找到的唯一方法是使用 Query 而不是 QueryRow,但这不方便,因为每次我想获取单行数据时都需要添加 for rows.Next() { ..

英文:

I want to fetch one row from an sql database. I use the following code:

var name string
row := db.Con().QueryRow("SELECT name FROM users WHERE id = 2;")
err := row.Scan(&name)

if err != nil {
    // log the error
}

For example: if a user with id=2 doesn't exist, then the method Scan returns an error.

Question:

Is there a way to avoid this error when a row doesn't exist? Because it's absolutely normal and I don't want to log such errors.

The only way I found is to use Query instead of QueryRow, but it is not convenient because I have to add for rows.Next() { .. every time when I want to fetch single row.

答案1

得分: 56

只需在记录日志之前检查不希望记录的错误:

var name string
row := db.Con().QueryRow("SELECT name FROM users WHERE id = 2;")
err := row.Scan(&name)

if err != nil && err != sql.ErrNoRows {
    // 记录错误日志
}
英文:

Simply check for the error you don't want to log before logging:

var name string
row := db.Con().QueryRow("SELECT name FROM users WHERE id = 2;")
err := row.Scan(&name)

if err != nil && err != sql.ErrNoRows {
    // log the error
}

答案2

得分: 0

你可以直接扫描返回的行,我首先检查它是否为nil。

if row != nil {
  err := row.Scan()
}

我认为你也可以使用pgx v4作为你的数据库驱动程序,它不会将没有行作为错误返回。

英文:

You can just scan the returned row, I check first that it is not nil.

if row != nil {
  err := row.Scan()
}

I think you can also use pgx v4 for your db driver and it doesn't return no rows as an error.

huangapple
  • 本文由 发表于 2017年3月29日 19:06:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/43091774.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定