douzhong6480 2015-12-18 07:00
浏览 155
已采纳

为什么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.

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

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失