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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。