如何在tryCatch和PostgreSQL中使用dbGetQuery?
我尝试使用如何在tryCatch和PostgreSQL中使用dbGetQuery?,r,postgresql,R,Postgresql,我尝试使用tryCatch从R查询我的PostgreSQL数据库。 基本上查询是有效的,但我无法捕获错误并对其作出反应。这里有一个例子 insert_rows <- function(dframe,con){ out <- list() for(i in 1:nrow(dframe)){ query <- .... some insert statement tryCatch({dbGetQuery(con,query)},error=function(e) print("c
tryCatch
从R查询我的PostgreSQL数据库。
基本上查询是有效的,但我无法捕获错误并对其作出反应。这里有一个例子
insert_rows <- function(dframe,con){
out <- list()
for(i in 1:nrow(dframe)){
query <- .... some insert statement
tryCatch({dbGetQuery(con,query)},error=function(e) print("caught"))
}
}
insert_rows使用dbSendQuery
发送insert语句。在这种情况下,tryCatch将捕获异常:
tryCatch({
dbSendQuery(con, "insert into wrongtable values(1, 2, 3)")
},
error = function(e) print(e)
)
对于使用dbGetQuery(我不知道它为什么失败),有一个解决方法-
调用postgresqlexectement
和postgresqlFetch
而不是dbGetQuery
:
tryCatch({
res <- postgresqlExecStatement(con, "select * from thereisnotablewiththisname")
postgresqlFetch(res)
},
error = function(e) print(e),
warning = function(w) print(w)
)
tryCatch({
resdbSendquery
确实有效。我不知道为什么我从来没有考虑过它。尽管理解dbGetQuery
在这件事上失败的原因会很有趣。@Mattbanert我前一段时间一直在解决这个问题。这是非R代码支持RPostgreSQL编写过程中固有的问题(我认为是C/C++,我已经有一段时间没有看过了)。它将错误发送到控制台,而不会在R中引发错误。这是非常有用的,我对sqldf也有同样的问题,我不能用trycatch语句来解决这个问题