how to pass value stored in r variable to a column in where clause of postgresql query in R

时间秒杀一切 提交于 2019-12-24 04:29:13

问题


I am using RPostgresql and DBI in RStudio.

library(RPostgreSQL)
library(DBI)
#save password
prod_pw <- {
  "my_pass"
}

 # make db connection
 con <- dbConnect(RPostgreSQL::PostgreSQL(), dbname = 'my_dbname', 
                        host = 'my_host',
                        port = 5432, # or any other port
                        user = 'user_name',
                        password = prod_pw)


# save query
myquery<- 'select count(*), state from results where date=\'2018-11-10\';'


#run query
my_query_stats<-dbGetQuery(con,myquery)

However I want to automate this, such a way that

the date can be either input from the user, or at minimum use the system date at the time of running the script.

What I tried: ex:

 this_date<-Sys.Date()
#or accept from user
this_date<- readline("Please Enter Date\n")  
# Please Enter Date2018-11-30
# this_date
# [1] "2018-11-30"

    myquery<- 'select count(*), state from results where date=this_date;'
    dbGetQuery(con,myquery) # didn't work, null value returned.

myquery<- 'select count(*), state from results where date=\'this_date\';'
    dbGetQuery(con,myquery) # didn't work, null value returned.

 myquery<- 'select count(*), state from results where date=\"this_date\";'
dbGetQuery(con,myquery) # didn't work, returned null value.

Please advise on how to accept value from user and send that to the psql query's date field.


回答1:


try this

this_date = "2018-11-30"


 string = paste("select count(*), state from results where date= 
 TO_DATE(this_date,'YYYYMMDD')")

 rs = dbGetQuery(connection,string)


来源:https://stackoverflow.com/questions/53605747/how-to-pass-value-stored-in-r-variable-to-a-column-in-where-clause-of-postgresql

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