How do you use a dynamic table name for a prepared INSERT
statement for the pq postgres driver? At the moment I've got a test table with id SERIAL
and values TEXT
columns, and this statement is failing:
stmt, err := db.Prepare("INSERT INTO $1(values) VALUES($2);")
if err != nil {
log.Fatal(err)
}
That's failing with:
pq: syntax error at or near "$1"
If I can only use placeholders for values and not table names, is there a way around using Sprintf
here? The table name contains a string
from user input and although I can sanitize it it will slow down the insert a bit compared to letting Postgres return an error on an prepared statement.
Sprintf
, but make sure to sanitize the table name down to only those characters allowed in table names per the database's documentation. – Martenmap
. – Portion6
). Whitelist them and quote them (manually since there is AFAIK no "quote identifier" function in the database interface) and useSprintf
. – Vast