duanju7199 2016-07-24 18:48
浏览 565
已采纳

使用sql.ErrNoRows的数据库/ sql中的示例崩溃和烧伤

I have a small Go program which uses a a postgresql db. In it there is a query which can return no rows, and the code I'm using to deal with this isn't working correctly.

    // Get the karma value for nick from the database.
func getKarma(nick string, db *sql.DB) string {
    var karma int
    err := db.QueryRow("SELECT SUM(delta) FROM karma WHERE nick = $1", nick).Scan(&karma)
    var karmaStr string
    switch {
    case err == sql.ErrNoRows:
        karmaStr = fmt.Sprintf("%s has no karma.", nick)
    case err != nil:
        log.Fatal(err)
    default:
       karmaStr = fmt.Sprintf("Karma for %s is %d.", nick, karma)
    }
    return karmaStr
}

This logic is taken directly from the Go documentation. When there are no rows corresponding to nick, the following error occurs:

2016/07/24 19:37:07 sql: Scan error on column index 0: converting driver.Value type <nil> ("<nil>") to a int: invalid syntax

I must be doing something stupid - clues appreciated.

  • 写回答

2条回答 默认 最新

  • dongshen4129 2016-07-25 02:33
    关注

    I believe your issue is that you're getting a NULL value back from the database, which go translates into nil. However, you're scanning into an integer, which has no concept of nil. One thing you can do is scan into a type that implements the sql.Scanner interface (and can handle NULL values), e.g., sql.NullInt64.

    In the example code in the documentation, I'd assume they have a NOT NULL constraint on the username column. I think the reason for this is because they didn't want to lead people to believe that you have to use NULL-able types across the board.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料