doucong3048 2014-10-30 21:41
浏览 66
已采纳

当此类行不存在时,Go func(* DB)查询返回

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条回答 默认 最新

  • douyan4958 2014-10-30 21:52
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离