Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

postgresql

go

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?

like image 403
robochat Avatar asked Mar 12 '15 11:03

robochat


1 Answers

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)
like image 188
Tino Avatar answered Oct 22 '22 13:10

Tino