英文:
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 = "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)
However I get the error
pq: syntax error at or near "$1"
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("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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论