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 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程