duanju7199
duanju7199
2016-07-24 18:48
浏览 355

使用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
    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.

    点赞 评论
  • doutouhe5343
    doutouhe5343 2016-07-24 20:52

    I reworked the code to get the results I wanted.

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

    Tempted to submit a documentation patch of some sort to the database/sql package.

    点赞 评论

相关推荐