15

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?

3
  • have you tried ? and not $1 Commented Mar 12, 2015 at 11:58
  • 2
    It gives the same error (i.e. syntax error at or near "?"). Anyway, I thought that the pq module used $1 ? Commented Mar 12, 2015 at 12:02
  • hmmm... can you try and make your query a single multi-line string using backticks? Not that I think it would matter but otherwise things seem okay, and it's a better practice in terms of GC pressure and cpu performance anyway. Commented Mar 12, 2015 at 12:13

1 Answer 1

13

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)
Sign up to request clarification or add additional context in comments.

3 Comments

@Tino when you say "You're right about $1 and ?.", what do you mean by it?
I'm stuck with the same problem.
@Obi Wan - PallavJha you have to specify its type

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.