kRazzy R
kRazzy R

Reputation: 1589

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

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.

Upvotes: 2

Views: 816

Answers (1)

Zeeshan
Zeeshan

Reputation: 1238

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)

Upvotes: 2

Related Questions