Home:ALL Converter>RPostgreSQL - Passing Parameter in R to a Query in RPostgreSQL

RPostgreSQL - Passing Parameter in R to a Query in RPostgreSQL

Ask Time:2018-08-02T16:07:10         Author:Daniel

Json Formatter

Question: How do I pass a variable in the RPostgreSQL query?

Example: In the example below I try to pass the date '2018-01-03' to the query

library(RPostgreSQL)

dt <- '2018-01-03'

connect <- dbConnect(PostgreSQL(), 
                 dbname="test",
                 host="localhost",
                 port=5432,
                 user="user", 
                 password="...")
result <- dbGetQuery(connect,
                "SELECT * FROM sales_tbl WHERE date = @{dt}")

Author:Daniel,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/51648611/rpostgresql-passing-parameter-in-r-to-a-query-in-rpostgresql
Paul :

You can use paste0 to generate your query and pass it to dbGetQuery:\n\nlibrary(RPostgreSQL)\n\ndt <- '2018-01-03'\n\nconnect <- dbConnect(PostgreSQL(), \n dbname=\"test\",\n host=\"localhost\",\n port=5432,\n user=\"user\", \n password=\"...\")\n\nquery <- paste0(\"SELECT * FROM sales_tbl WHERE date='\", dt, \"'\")\nresult <- dbGetQuery(connect, query)\n",
2018-08-02T08:15:36
yy