签名是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/