【问题标题】:golang syntax error at or near "$1" in postgrespostgres中“$ 1”或附近的golang语法错误
【发布时间】:2015-03-12 21:34:55
【问题描述】:

我正在尝试使用 sql 模块在 go 中执行查询。

var from string = "2015-03-01 00:00:00"    
rows, err := db.Query("select time, val from table where " +
                              "time >= extract(epoch from timestamp with time zone $1)::int4 " +
                              "and time < extract(epoch from timestamp with time zone '2015-03-01 00:15:10')::int4 " +
                              "order by time asc",from)

但是我得到了错误

pq: syntax error at or near "$1"

如果我直接输入 epoch 值,那么查询将起作用,并且当我尝试不带任何变量(即使用硬编码的查询)时,查询将起作用。 那么问题出在哪里?

【问题讨论】:

  • 你试过?而不是$1
  • 它给出了同样的错误(即syntax error at or near "?")。反正我以为pq模块用了$1
  • hmmm...您可以尝试使用反引号使您的查询成为单个多行字符串吗?并不是说我认为这很重要,但其他方面看起来还不错,而且无论如何在 GC 压力和 cpu 性能方面这是一个更好的做法。

标签: postgresql go


【解决方案1】:

$1? 是对的。

它抱怨$1 语法无效的原因是类型转换。可以这样写:

rows, err := db.Query("select time, val from table where " +
                          "time >= extract(epoch from $1::timestamp with time zone)::int4 " +
                          "and time < extract(epoch from timestamp with time zone '2015-03-01 00:15:10')::int4 " +
                          "order by time asc",from)

【讨论】:

  • @Tino 当你说"You're right about $1 and ?."时,你是什么意思?
  • 我遇到了同样的问题。
  • @Obi Wan - PallavJha 你必须指定它的类型
猜你喜欢
  • 2022-01-17
  • 2014-07-10
  • 2021-07-13
  • 2014-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-22
相关资源
最近更新 更多