3

I am using Go to execute a query on a PostgreSQL DB. Note that in the DB id is type bigint.

db.Exec("UPDATE tags SET association_count = association_count - 1 WHERE id=?;", id)

When I run this code, I get a SQL error

operator does not exist: bigint =?

From what I can tell this is caused by a typing mismatch between the id and the ?. I've tried casting with :: but it throws an error, and haven't found anything about this. Interestingly, if there is a space, like id = ? it throws a general syntax error. Any idea how to cast or work around this?

4
  • It is not a type problem. The problem is that the placeholder is not being replaced or the id variable value is ? May 23, 2016 at 17:44
  • Could the problem be the semicolon? May 23, 2016 at 17:48
  • @ClodoaldoNeto What do you mean by the id variable value is ?? Like Postgres doesn't know which id it's looking at?
    – cfatt10
    May 23, 2016 at 17:49
  • I mean somehow the id variable has been set to ?. Check the db.Exec syntax May 23, 2016 at 17:58

1 Answer 1

7

Postgres uses $# for placeholders postgres docs

When creating the prepared statement, refer to parameters by position, using $1, $2, etc. A corresponding list of parameter data types can optionally be specified. When a parameter's data type is not specified or is declared as unknown, the type is inferred from the context in which the parameter is used (if possible). When executing the statement, specify the actual values for these parameters in the EXECUTE statement. Refer to EXECUTE for more information about that.

so try

result, err := db.Exec(`
    UPDATE tags
    SET association_count = association_count - 1
    WHERE id=$1;`, id
)

Here is what result looks like

UPDATE: a_horse_with_no_name makes a good point. This depends on what client library you are using. I assumed it was pq since that is popular for postgres in golang.

3
  • 3
    Note that the comment from the manual refers to statement inside a procedural language e.g PL/pgSQL. The placeholder handling from a "client" language is handled by language's driver. In JDBC the placehoder is ? and $1 wouldn't work there. So in this case apparently the driver for Go uses the same syntax as the backend. But the quote from the manual doesn't really refer to prepared statements from an application language
    – user330315
    May 23, 2016 at 19:33
  • @a_horse_with_no_name Thats a good point. I was assuming the OP was using pq which mimics postgres's $1 syntax. May 23, 2016 at 19:37
  • 1
    @poopoothegorilla another small point: you need a comma after id :)
    – InkyDigits
    May 23, 2016 at 23:46

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.