go func(*DB) 不存在该行时查询返回

标签 go

签名是func (db *DB) Query(query string, args ...interface{}) (*Rows, error)

如果查询和调用是:Go func (*DB) Query 返回什么:

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

userstable 表中没有这样的行时。

它是返回一个非零的error还是返回空字符串值作为Result并且非nil的error只有在错误时才返回发生了吗?

最佳答案

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

来自 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.

当使用 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) {
    //handle this case
}

关于go func(*DB) 不存在该行时查询返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26663833/

相关文章:

go - 如何正确处理 runtime.Caller(0) 上的错误

google-app-engine - 定义了一个带有绑定(bind)参数但得到 404 的 Goji 路由

go - 相当于Java在GoLang中将Object作为方法参数传递

performance - 迄今为止的 CSV 和 float

go - 无法使用来自本地运行的 Kafka 服务器的消息,使用 Golang Sarama 包

go - 将 go 项目分解为子文件夹

go - 如何在 Go 中将日期转换为带毫秒的 RFC3339 扩展日期字符串?

go - Go lang函数返回多个值如何使用可变参数传递给其他函数

go - 如何在函数中修改 GORM DB 指针?

gcc - golang 在使用和不使用 cgo 进行构建时使用的汇编程序