I have a data.frame that I am trying to append to a table in a PostgreSQL database in R
using the DBI
package.
library(DBI)
library(RPostgreSQL)
mydrv <- dbDriver(drvName = "PostgreSQL")
mydbcon <- dbConnect(drv = mydrv , host = myhostname , dbname = mydbname , username = myusername , password = mypassword )
If I try to do dbAppendTable
, it fails with a strange error message:
dbAppendTable( conn = mydbcon , name = mytable , value = mydata )
Error in postgresqlExecStatement(conn, statement, ...) : RS-DBI driver: (could not Retrieve the result : ERROR: syntax error at or near "," LINE 4: (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
But if I do it in two steps with sqlAppendTable
and dbExecute
, then it works fine:
append_cmd <- sqlAppendTable( con = mydbcon , table = mytable , values = mydata , row.names = FALSE )
dbExecute( conn = mydbcon , statement = append_cmd )
The documentation for dbAppendTable
says:
The dbAppendTable() method assumes that the table has been created beforehand, e.g. with dbCreateTable(). The default implementation calls sqlAppendTableTemplate() and then dbExecute() with the param argument. Backends compliant to ANSI SQL 99 which use ? as a placeholder for prepard queries don't need to override it. Backends with a different SQL syntax which use ? as a placeholder for prepared queries can override sqlAppendTable(). Other backends (with different placeholders or with entirely different ways to create tables) need to override the dbAppendTable() method.
The part about '?'
being the placeholder seems relevant, but I don't understand how it fits in. Why does PostgreSQL not satisfy this? Why do I have to do it in two steps to get it to work?
dbAppendTable
does seem to work with a connection created using the RPostgres package. – StravinskydbAppendTable
anddbExecute
fail with either RPostgres or RPostgreSQL connections if you try to set the table name using a schema qualifier, e.g.,table = c('schema_name','table_name')
ortable = 'schema_name.table_name'
, however, the following does appear to work:dbWriteTable(conn = con, name = c('schema_name','table_name'), value = mytable, overwrite = F, append = T, row.names = F)
. – Stravinsky