不能使用RPostgres dbWriteTable在PostgreSQL中写入时间戳

时间:2016-10-24 10:16:51

标签: r dplyr r-dbi

我尝试使用tibble包将R data.frame对象(或Postgres)写入RPostgres数据库。在文档之后,我尝试使用dbWriteTable函数。

但是,我意识到方法中没有field.types的规范。在这里,我提供了一个最小的示例,您可以在输入具有POSIXct时间戳(并将时间戳被解释为字符时传递)时看到方法失败。

library(dplyr)
library(DBI)
library(RPostgres)
library(tibble)

conn <- dbConnect(RPostgres::Postgres(),
  host = url$host,
  port = url$port,
  dbname = url$dbname,
  user = url$user,
  password = url$password
)

test <- tibble(
  words = c("hallo","ja", "nein"),
  value = c(3,4,5),
  time= as.POSIXct(c("2016-05-04 04:32","2016-06-02 09:37","2016-07-12 10:43")))
test2 <- tibble(
  words = c("hallo","ja", "nein"),
  value = c(3,4,5),
  time= c("2016-05-04 04:32","2016-06-02 09:37","2016-07-12 10:43"))

dbWriteTable(conn = conn, name = "words", value = test)
> Error in eval(substitute(expr), envir, enclos) :
> ERROR:  invalid input syntax for type real: "2016-05-04 04:32:00"
> CONTEXT:  COPY words, line 1, column time: "2016-05-04 04:32:00"

dbWriteTable(conn = conn, name = "words2", value = test2)
> [1] TRUE

是否有人知道使用PostgresR中使用时间戳编写表格的更好方法?

1 个答案:

答案 0 :(得分:0)

PostgreSQL包中使用RPostgreSQL驱动程序有效。此外,第三个时间戳的格式与as.POSIXct的默认值不匹配 - 小时数字太多。所以我将"2016-07-12 010:43"更改为"2016-07-12 10:43",您应该会发现它工作正常。

library(dplyr)
library(DBI)
library(RPostgreSQL)
library(tibble)

#connect to db    
url <- list(user="postgres",password="postgres",dbname="test")

conn <- dbConnect(drv="PostgreSQL", user=url$user, password=url$password, dbname = url$dbname)


test <- tibble(
  words = c("hallo","ja", "nein"),
  value = c(3,4,5),
  time= as.POSIXct(c("2016-05-04 04:32","2016-06-02 09:37","2016-07-12 10:43")))
test2 <- tibble(
  words = c("hallo","ja", "nein"),
  value = c(3,4,5),
  time= c("2016-05-04 04:32","2016-06-02 09:37","2016-07-12 010:43"))


dbWriteTable(conn = conn, name = "words", value = test)
  

[1] TRUE

dbWriteTable(conn = conn, name = "words2", value = test2)
  

[1] TRUE

dbDisconnect(conn)