4

我最近开始使用 RODBC 连接到 PostgreSQL,因为我无法让 RPostgreSQL 在 Windows x64 中编译和运行。我发现两个包之间的读取性能相似,但写入性能则不然。例如,使用 RODBC(其中 z 是 ~6.1M 行数据帧):

library(RODBC)
con <- odbcConnect("PostgreSQL84")

#autoCommit=FALSE seems to speed things up
odbcSetAutoCommit(con, autoCommit = FALSE)
system.time(sqlSave(con, z, "ERASE111", fast = TRUE))

user  system elapsed
275.34  369.86 1979.59 

odbcEndTran(con, commit = TRUE)
odbcCloseAll()

而对于使用 RPostgreSQL(32 位以下)的相同 ~6.1M 行数据帧:

library(RPostgreSQL)
drv <- dbDriver("PostgreSQL")
con <- dbConnect(drv, dbname="gisdb", user="postgres", password="...")
system.time(dbWriteTable(con, "ERASE222", z))

user  system elapsed 
467.57   56.62  668.29 

dbDisconnect(con)

因此,在这个测试中,RPostgreSQL 在写表方面的速度大约是 RODBC 的 3 倍。无论数据框中的行数如何,这个性能比似乎都保持不变(但列数的影响要小得多)。我确实注意到 RPostgreSQL 使用了类似的东西,COPY <table> FROM STDIN而 RODBC 发出了一堆INSERT INTO <table> (columns...) VALUES (...)查询。我还注意到 RODBC 似乎为整数选择 int8,而 RPostgreSQL 在适当的地方选择 int4。

我需要经常做这种数据帧复制,所以我非常感谢任何关于加速 RODBC 的建议。例如,这只是 ODBC 固有的,还是我没有正确调用它?

4

1 回答 1

1

似乎没有直接的答案,所以我会发布一个笨拙的解决方法,以防它对任何人都有帮助。

Sharpie 是正确COPY FROM的——这是迄今为止将数据输入 Postgres 的最快方法。根据他的建议,我编写了一个函数,可以显着提升RODBC::sqlSave(). 例如,写入一个 110 万行(24 列)的数据帧需要 960 秒(经过),sqlSave而使用下面的函数需要 69 秒。我没想到会这样,因为数据先写入磁盘,然后再写入数据库。

library(RODBC)
con <- odbcConnect("PostgreSQL90")

#create the table
createTab <- function(dat, datname) {

  #make an empty table, saving the trouble of making it by hand
  res <- sqlSave(con, dat[1, ], datname)
  res <- sqlQuery(con, paste("TRUNCATE TABLE",datname))

  #write the dataframe
  outfile = paste(datname, ".csv", sep = "")
  write.csv(dat, outfile)
  gc()   # don't know why, but memory is 
         # not released after writing large csv?

  # now copy the data into the table.  If this doesn't work,
  # be sure that postgres has read permissions for the path
  sqlQuery(con,  
  paste("COPY ", datname, " FROM '", 
    getwd(), "/", datname, 
    ".csv' WITH NULL AS 'NA' DELIMITER ',' CSV HEADER;", 
    sep=""))

  unlink(outfile)
}

odbcClose(con)
于 2011-04-22T14:20:38.530 回答