douzhong6480
2015-12-18 07:00
浏览 139

为什么go-sql-driver无法在MySQL bigint字段中处理NULL?

I am using go-sql-driver to connect to MySQL database. In one of my table I am using a field called queue_length as BIGINT. This field is NULL by default. When I try to query all the fields from the table using go-sql-driver in Golang, the fields after queue_length are not coming in the result set including queue_length.

In my use case,

Table fields [unique_id, qid, title, text, queue_length, user_id, date_created, last_updated]

When I execute the following code I am getting values for fields before queue_length but [queue_length, user_id, date_created, last_updated] fields are not coming in result set.

But if I don't select queue_length, all fields are coming in result set. I am scanning queue_length in queueLength variable in code which is of type int64. The value coming from table is NULL. I tried type conversion also. Didn't work.

Is this a bug in go-sql-driver or am I doing anything wrong? Could anyone help me with this?

func GetQueues(uniqueId string) ([]*objects.Queue, error) {
    db, err := GetDBConnection()
    defer db.Close()

    rows, err := db.Query("SELECT qid, title, text, queue_length, user_id, date_created, last_updated FROM queue WHERE unique_id = ?", uniqueId)
    if err != nil {
        panic(err.Error())
    }
    defer rows.Close()

    var qId             string
    var title           string
    var text            string
    var userId          string
    var dateCreated     string
    var lastUpdated     string
    var queueLength     int64
    var queue           *objects.Queue
    var queues          []*objects.Queue

    for rows.Next() {
        err           = rows.Scan(&qId, &title, &text, &queueLength, &userId, &dateCreated, &lastUpdated)
        queue         = &objects.Queue{ QId: qId, Title: title, Text: text, UniqueId: uniqueId, UserId: userId, DateCreated: dateCreated, LastUpdated: lastUpdated, QueueLength: queueLength }
        queues        = append(queues, queue)
    }
    err = rows.Err()

    if err != nil {
        panic(err.Error())
        return nil, err
    }
    return queues, err
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongtang1909 2015-12-18 12:58
    已采纳

    queueLength should be a NullInt64 instead of an int64.

    var queueLength sql.NullInt64
    

    In Go ints can't be nil so there's no way for Scan to save NULL in queueLength.

    点赞 评论
  • dongqian5569 2015-12-21 13:37

    I use this tool for Null and Zero fields, it includes many data types.

    The github url is https://github.com/guregu/null

    点赞 评论

相关推荐 更多相似问题