douduanque5850 2015-10-13 03:07
浏览 57
已采纳

尝试在Go中扫描到int64指针时出现错误

I'm getting this error

 Scan error on column index 1: converting string "<nil>" to a int64:
 strconv.ParseInt: parsing "<nil>": invalid syntax

when trying to run this simple code:

var id int64
var replyTo *int64
replyTo = new(int64)

query := `
    SELECT id, reply_to
    FROM message
    WHERE id = 211
    LIMIT 1;
`
if err := sql.DB.QueryRow(query).Scan(&id, replyTo); err != nil {
    log.Println(err)
}

spew.Dump(id, replyTo)

The table I am selecting from looks like this:

enter image description here

If I change the select query to: WHERE id = 210, instead of 211 then it works.

The sql.DB is just an instance of the sqlx library.

var DB *sqlx.DB

I am using a pointer to be able to catch NULL columns from the database. I am using a pointer because I am not sure if sql.NullInt64 works well with the sqlx library.

Why do I get this error? What can I do about it?

  • 写回答

1条回答 默认 最新

  • dtsjq28482 2015-10-13 05:17
    关注

    Scan needs a pointer to your pointer for this to work :

    var id int64
    var replyTo *int64
    replyTo = new(int64)
    
    query := `
        SELECT id, reply_to
        FROM message
        WHERE id = 211
        LIMIT 1;
    `
    // The change is here : &replyTo instead of just replyTo
    if err := sql.DB.QueryRow(query).Scan(&id, &replyTo); err != nil {
        log.Println(err)
    }
    
    spew.Dump(id, replyTo)
    

    Then don't forget to test for replyTo == nil before using the value *replyTo

    Alternative solution : use a sql.NullInt64 : https://golang.org/pkg/database/sql/#NullInt64

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数