英文:
go with sqlx NamedQuery timestamp works with date but not with datetime. NamedQuery vs Query
问题
以下是翻译好的内容:
rows, err := db.NamedQuery(`SELECT ts FROM test_table WHERE ts > '1999-01-08 04:05:06';`, map[string]interface{})
上述代码给出了以下错误:
在第74个字符处读取命名参数时出现意外的`:`。
panic: 运行时错误:无效的内存地址或空指针解引用
这很奇怪,因为下面的代码片段
rows, err := db.NamedQuery(`SELECT ts FROM test_table WHERE ts > '1999-01-08';`, map[string]interface{})
运行时没有错误。
两者之间的区别是在输入中添加了时间。
我改用`db.Query`而不是sqlx方法`db.NamedQuery`,问题得到解决。
现在我明白了,我应该将输入作为参数传递给NamedQuery。
通常如何编写这样的查询语句,为什么要使用NamedQuery而不是Query?
英文:
rows, err := db.NamedQuery(`SELECT ts FROM test_table WHERE ts > '1999-01-08 04:05:06';`, map[string]interface{}{})
The code above gave me the following error:
unexpected `:` while reading named param at 74
panic: runtime error: invalid memory address or nil pointer dereference
This is strange, as the following snippet,
rows, err := db.NamedQuery(`SELECT ts FROM test_table WHERE ts > '1999-01-08';`, map[string]interface{}{})
runs without fault.
The difference between the two, is adding time to the input.
I resorted to using db.Query
instead of the sqlx method db.NamedQuery
which solved my problem.
I now see that I should have passed my input to NamedQuery as a parameter.
How does one typically write such a query and why would you use NamedQuery rather than Query?
答案1
得分: 1
为什么要使用NamedQuery而不是Query?
使用命名参数的查询更容易解析。
通常如何编写这样的查询?
layout := "2006-01-02 15:04:05"
ts, err := time.Parse(layout, "1999-01-08 04:05:06")
if err != nil {
return err
}
arg := map[string]interface{}{"ts": ts}
rows, err := db.NamedQuery(`SELECT ts FROM test_table WHERE ts > :ts`, arg)
if err != nil {
return err
}
英文:
> why would you use NamedQuery rather than Query?
Queries that use named parameters are easier for the human to parse.
> How does one typically write such a query
layout := "2006-01-02 15:04:05"
ts, err := time.Parse(layout, "1999-01-08 04:05:06")
if err != nil {
return err
}
arg := map[string]interface{}{"ts": ts}
rows, err := db.NamedQuery(`SELECT ts FROM test_table WHERE ts > :ts`, arg)
if err != nil {
return err
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论