go with sqlx NamedQuery timestamp works with date but not with datetime. NamedQuery vs Query

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

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
}

huangapple
  • 本文由 发表于 2022年1月30日 22:57:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/70915833.html
匿名

发表评论

匿名网友

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

确定