Skip to content

INSERT with placeholders via dbExecute does not work #391

Open

Description

@stefan-m-lenz

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?

Activity

  1. krlmlr commented on Jan 31, 2022

    @krlmlr
    Member

    Thanks. Do you need $1 and $2 instead of ? ?

    What's the best place to document this?

  2. stefan-m-lenz commented on Feb 1, 2022

    @stefan-m-lenz
    Author

    Thank you very much for the fast response.

    Yes, this works:

    dbExecute(
      con,
      "INSERT INTO cars (speed, dist) VALUES ($1, $2)",
      params = list(4:7, 5:8)
    )

    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.

  3. medeirosramos commented on Sep 25, 2024

    @medeirosramos
  4. krlmlr commented on Sep 26, 2024

    @krlmlr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions