在Go语言中,尝试将输入扫描到int64指针时出现错误。

huangapple go评论154阅读模式
英文:

Getting error when trying to scan into an int64 pointer in Go

问题

我遇到了这个错误:

在运行这段简单代码时出现了错误:

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

我正在尝试运行以下代码:

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)

我选择的表格如下所示:

在Go语言中,尝试将输入扫描到int64指针时出现错误。

如果我将选择查询更改为:WHERE id = 210,而不是211,那么它就可以工作。

sql.DB只是sqlx库的一个实例。

var DB *sqlx.DB

我使用指针来捕获数据库中的NULL列。我使用指针是因为我不确定sql.NullInt64在sqlx库中是否有效。

为什么会出现这个错误?我该怎么办?

英文:

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:

在Go语言中,尝试将输入扫描到int64指针时出现错误。

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

得分: 1

Scan需要一个指向指针的指针才能正常工作:

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

query := `
    SELECT id, reply_to
    FROM message
    WHERE id = 211
    LIMIT 1;
`
// 改动在这里:&replyTo 而不是 replyTo
if err := sql.DB.QueryRow(query).Scan(&id, &replyTo); err != nil {
    log.Println(err)
}

spew.Dump(id, replyTo)

然后在使用值 *replyTo 之前,不要忘记测试 replyTo == nil

另一种解决方案:使用 sql.NullInt64:https://golang.org/pkg/database/sql/#NullInt64

英文:

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

huangapple
  • 本文由 发表于 2015年10月13日 11:07:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/33093450.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定