问题
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