RPostgreSQL-将R中的参数传递给RPostgreSQL中的查询

时间:2018-08-02 08:07:11

标签: r parameter-passing rpostgresql

问题:如何在RPostgreSQL查询中传递变量?

示例:在下面的示例中,我尝试将日期“ 2018-01-03”传递给查询

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

2 个答案:

答案 0 :(得分:2)

您可以使用paste0生成查询并将其传递给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)

答案 1 :(得分:0)

最安全的方法是按照here

设置查询参数

示例:

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)

通过传递?,您正在清理查询以避免SQL注入攻击。

我想做的另一件事是创建.Renviron文件来存储我的凭证。例如,对于上面的连接,.Renviron文件将如下所示。

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

保存文件,然后重新启动RStudio(以在启动时加载.Renviron文件)。然后使用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"))