I want to pass values contained in variables as inputs to a postgresql query using R.
Currently I'm following where it gives as example:
https://db.rstudio.com/best-practices/run-queries-safely/
Using a parameterised query with DBI requires three steps.
You create a query containing a ? placeholder and send it to the database with dbSendQuery():
airport <- dbSendQuery(con, "SELECT * FROM airports WHERE faa = ?")
Use dbBind() to execute the query with specific values, then dbFetch() to get the results:
dbBind(airport, list("GPT"))
dbFetch(airport)
## faa name lat lon alt tz dst
## 1 GPT Gulfport-Biloxi 30.40728 -89.07011 28 -6 A
Once you’re done using the parameterised query, clean it up by calling dbClearResult()
dbClearResult(airport)
Here is my current setup.
install.packages("RPostgres")
#https://github.com/r-dbi/RPostgres
require(RPostgres)
require(DBI)
require(tidyr)
# RPostgreSQL::PostgreSQL()
# make connection
con <- dbConnect(RPostgres::Postgres(), dbname = 'test',
host = 'mydbtest.com',
port = 1234, # or any other port specified by your DBA
user = 'test',
password = 'test')
rs = dbGetQuery(con, "select count(*),state from sales where created > ? and created < ? group by state")
What I want to do: Pass two dates as inputs to the query.
Error I get:
> rs = dbGetQuery(prod_con, "select count(*),state from sales where created > ? and created < ? group by state")
Error in result_create(conn@ptr, statement) :
Failed to prepare query: ERROR: syntax error at or near "and"
LINE 1: ...count(*),state from sales where created > ? and create...
Question1 How do I get around this error, and what is causing it? I'm using the ? placeholder as given in the example.
Question 2
How do I pass multiple values to the two ?
s
like this
dbBind(con, list("2019-06-21","2019-06-22")) ?
References:
how to pass value stored in r variable to a column in where clause of postgresql query in R
RPostgreSQL - Passing Parameter in R to a Query in RPostgreSQL