英文:
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)
我选择的表格如下所示:
如果我将选择查询更改为: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:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论