You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
INSERT with placeholders via dbExecute does not work #391
I try to execute an INSERT statement with placeholders in my Postgres DB. This gives me a syntax error.
This problem occurs also with the example from the DBI package for the DBI::dbExecute function.
The following is the code from the example for DBI::dbExecute, with the first line for the connection replaced with a Postgres data base,
con<- dbConnect(RPostgres::Postgres(),
dbname="test",
user="postgres",
password="password")
dbWriteTable(con, "cars", head(cars, 3))
dbReadTable(con, "cars") # there are 3 rows
dbExecute(
con,
"INSERT INTO cars (speed, dist) VALUES (1, 1), (2, 2), (3, 3)"
)
dbReadTable(con, "cars") # there are now 6 rows# Pass values using the param argument:
dbExecute(
con,
"INSERT INTO cars (speed, dist) VALUES (?, ?)",
params=list(4:7, 5:8)
)
dbDisconnect(con)
The first call to dbExecute works, but the second one with the placeholders yields an error:
Error: Failed to prepare query: FEHLER: Syntax error at »,«
LINE 1: INSERT INTO cars (speed, dist) VALUES (?, ?)
I use PostgreSQL version 14, R version 4.1.2 and a freshly installed DBI and RPostgres package on Windows 10.
Is this a bug or do I miss something?
I thought that all SQL dialects use a question mark as placeholder. Well, I was wrong. Thanks for helping me to learn this.
I would suggest to add a simple example for an INSERT or other statement that uses placeholders in the documentation. The README example could be a good place, as using placeholders is a practice that should be encouraged.
Additionally, the postgres-query documentation item ("Execute a SQL statement on a database connection") could be expanded with such a simple INSERT example and a brief explanation could be added there that PostgreSQL uses different placeholders.
Activity
krlmlr commentedon Jan 31, 2022
Thanks. Do you need
$1and$2instead of??What's the best place to document this?
stefan-m-lenz commentedon Feb 1, 2022
Thank you very much for the fast response.
Yes, this works:
I thought that all SQL dialects use a question mark as placeholder. Well, I was wrong. Thanks for helping me to learn this.
I would suggest to add a simple example for an INSERT or other statement that uses placeholders in the documentation. The README example could be a good place, as using placeholders is a practice that should be encouraged.
Additionally, the
postgres-querydocumentation item ("Execute a SQL statement on a database connection") could be expanded with such a simple INSERT example and a brief explanation could be added there that PostgreSQL uses different placeholders.medeirosramos commentedon Sep 25, 2024
krlmlr commentedon Sep 26, 2024