我在RStudio中使用RPostgresql和DBI。
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)
但是我想使它自动化
可以从用户输入日期,也可以至少在运行脚本时使用系统日期。
我尝试了什么: 例如:
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.
请告知如何接受用户的值并将其发送到psql查询的日期字段。
答案 0 :(得分:2)
尝试
this_date = "2018-11-30"
string = paste("select count(*), state from results where date=
TO_DATE(this_date,'YYYYMMDD')")
rs = dbGetQuery(connection,string)