RPostgreSQL - Passing Parameter in R to a Query in RPostgreSQL

有些话、适合烂在心里 提交于 2019-12-19 04:57:10

问题


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}")

回答1:


You can use paste0 to generate your query and pass it to dbGetQuery:

library(RPostgreSQL)

dt <- '2018-01-03'

connect <- dbConnect(PostgreSQL(), 
  dbname="test",
  host="localhost",
  port=5432,
  user="user", 
  password="...")

query <- paste0("SELECT * FROM sales_tbl WHERE date='", dt, "'")
result <- dbGetQuery(connect, query)



回答2:


The safest way is to parameterize the query as mentioned here

Example:

library(RPostgreSQL)

dt <- '2018-01-03'

connect <- dbConnect(drv = PostgreSQL(), 
  dbname ="test",
  host = "localhost",
  port = 5432,
  user = "user", 
  password = "...")

query <- "SELECT * FROM sales_tbl WHERE date= ?"
sanitized_query <- dbSendQuery(connect, query)
dbBind(sanitized_query, list(dt))
result <- dbFetch(sanitized_query)

Here by passing ? you are sanitizing your query to avoid SQL injection attacks.

Another thing I like to do is to create .Renviron file to store my credintials. For example, for the connection above, the .Renviron file will look like this.

dbname = test
dbuser = me
dbpass = mypass
dbport = 5432
dbhost = localhost

save the file, restart RStudio (to load the .Renviron file at startup). Then access the credentials using the Sys.getenv(variable)

#example:
connect <- dbConnect(drv = PostgreSQL(), 
  dbname = Sys.getenv("dbname"),
  host = Sys.getenv("dbhost"),
  port = Sys.getenv("dbport"),
  user = Sys.getenv("dbuser"), 
  password = Sys.getenv("dbpass"))


来源:https://stackoverflow.com/questions/51648611/rpostgresql-passing-parameter-in-r-to-a-query-in-rpostgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!