在PostgreSQL中,出现了类似于”$1″的Golang语法错误。

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

golang syntax error at or near "$1" in postgres

问题

我正在尝试使用Go语言的sql模块执行一个查询。

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值,那么查询将会正常工作,而且当我尝试在查询中不使用任何变量时,查询也能正常工作。所以问题是什么呢?

英文:

I am trying to execute a query in go using the sql module.

var from string = &quot;2015-03-01 00:00:00&quot;    
rows, err := db.Query(&quot;select time, val from table where &quot; +
                              &quot;time &gt;= extract(epoch from timestamp with time zone $1)::int4 &quot; +
                              &quot;and time &lt; extract(epoch from timestamp with time zone &#39;2015-03-01 00:15:10&#39;)::int4 &quot; +
                              &quot;order by time asc&quot;,from)

However I get the error

pq: syntax error at or near &quot;$1&quot;

If I put in the epoch values directly then the query will work and the query works when I try it without any variables i.e. with the query hardcoded.
So what is the problem?

答案1

得分: 12

你对$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)
英文:

You're right about $1 and ?.

The reason why it complains about invalid syntax with $1 is because of type cast. Put it like this:

rows, err := db.Query(&quot;select time, val from table where &quot; +
                          &quot;time &gt;= extract(epoch from $1::timestamp with time zone)::int4 &quot; +
                          &quot;and time &lt; extract(epoch from timestamp with time zone &#39;2015-03-01 00:15:10&#39;)::int4 &quot; +
                          &quot;order by time asc&quot;,from)

huangapple
  • 本文由 发表于 2015年3月12日 19:01:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/29007972.html
匿名

发表评论

匿名网友

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

确定