当不存在这样的行时,Go的`func (*DB) Query`会返回什么?

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

Go func (*DB) Query return when such a row does not exist

问题

func (*DB) Query 方法在查询结果为空时会返回一个非空的 error,而不会返回空字符串作为结果。只有在发生错误时才会返回非空的 error

英文:

Signature is func (db *DB) Query(query string, args ...interface{}) (*Rows, error).

What does Go func (*DB) Query return if the query and call is:

rows, err := db.Query("SELECT username FROM userstable WHERE username=$1", registerInstance.Username)

when there is no such row in the table userstable.

Does it return a non-nil error or return empty string value as Result and non-nil error is returned only when an error occurs?

答案1

得分: 1

在这种情况下,你肯定会想要使用QueryRow而不是Query(假设你只会得到一个具有相同用户名的用户)。

根据http://go-database-sql.org/retrieving.html

Go定义了一个特殊的错误常量,称为sql.ErrNoRows,当查询结果为空时,QueryRow()会返回该常量。在大多数情况下,需要将其作为特殊情况处理。应用程序代码通常不会将空结果视为错误,如果你不检查错误是否为这个特殊常量,就会导致意外的应用程序代码错误。

当使用Query时,你将使用以下代码循环遍历结果:

rows, err := db.Query("SELECT username FROM userstable WHERE username=$1", registerInstance.Username)
if err != nil {
    log.Fatal(err)
}
defer rows.Close()
var users []User
for rows.Next() {
    user := User{}
    err := rows.Scan(&user.Username)
    if err != nil {
        log.Fatal(err)
    }
    users = append(users, user)
}
rows.Close()
if len(users) == 0 {
    // 处理这种情况
}
英文:

In this case, you'll definitely want to use QueryRow instead of Query (assuming you'd only ever get one user with the same username).

From http://go-database-sql.org/retrieving.html
> Go defines a special error constant, called sql.ErrNoRows, which is returned from QueryRow() when the result is empty. This needs to be handled as a special case in most circumstances. An empty result is often not considered an error by application code, and if you don’t check whether an error is this special constant, you’ll cause application-code errors you didn’t expect.

When using Query, you'll be looping over the results with something like:

rows, err := db.Query("SELECT username FROM userstable WHERE username=$1", registerInstance.Username)
if err != nil {
    log.Fatal(err)
}
defer rows.Close()
var users []User
for rows.Next() {
    user = User{}
    err := rows.Scan(&user.Username)
    if err != nil {
        log.Fatal(err)
    }
    users = append(users, user)
}
rows.Close()
if (len(users) == 0) {
    //handle this case
}

huangapple
  • 本文由 发表于 2014年10月31日 05:41:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/26663833.html
匿名

发表评论

匿名网友

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

确定