SQL table name as variable to query

1.6k Views Asked by At

I am using the pgx library to populate a Postgres database in Go.

Following e.g. the tutorial here and this question, I construct my query like so:

// this works
tblinsert = `INSERT into tablename (id, body) VALUES ($1, $2) RETURNING id`
var id string
err := Connector.QueryRow(context.Background(), tblinsert, "value1", "value2").Scan(&id)
  • Question: I would like to supply the tablename as a variable to the query as well, e.g. change tblinsert to INSERT into $1 (id, body) VALUES ($2, $3)

  • Issue: the above code errors out and returns a "syntax error at or near "$1" (SQLSTATE 42601)" when I run:

      //this errors out
      err := Connector.QueryRow(context.Background(), tblinsert, "tablename", "value1", "value2").Scan(&id)`.
    

I do not fully understand why the error message even references the $ placeholder - I expected the query to do the string substitution here, just like for the VALUES.

I found similar questions in pure SQL here and here, so not sure if this is even possible. .

Any pointers on where I am going wrong, or where I can learn more about the $x syntax (I got the above to work using Sprintf, but this appears discouraged) are much appreciated - I am pretty new to both SQL and Go.

0

There are 0 best solutions below