我从R连接到PostgreSQL,我能够使用时间戳作为表名来编写表,但我无法提取值。
我使用了以下代码。
library(DBI)
con <- dbConnect(RPostgres::Postgres(),dbname = 'postgres',
host = 'hostname',
port = 5432,
user = 'username',
password = 'pwd')
tm<-paste0('job_status_',Sys.time())
dbWriteTable(con,tm,jbs)
dbGetQuery(con,paste0('select * from ',tm))
当我运行select
命令时,我得到以下语法错误。
Error in result_create(conn@ptr, statement) :
Failed to prepare query: ERROR: syntax error at or near "-"
LINE 1: select * from job_status_2019-03-12 04:33:08
任何人都可以帮我解决这个问题吗?!
由于您的表名包含字符- :
,因此需要引用"
来理解为表名。
dbGetQuery(con,paste0('select * from "',tm, '"'))
BTW。避免表名中的异常字符并将自己限制为字母,数字和下划线(_
)可能是个好主意。要实现这一点,你可以利用gsub()
。
tm<-gsub('-|:| ', '_', paste0('job_status_',Sys.time()))
dbWriteTable(con,tm,jbs)
dbGetQuery(con,paste0('select * from ',tm))