我尝试使用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"))
}
}
Run Code Online (Sandbox Code Playgroud)
当我创建错误(例如,通过向唯一的PK输入重复记录)时,确实看到了PostgreSQL错误和警告,但这是的标准打印输出RPostgreSQL。我tryCatch在其他上下文中使用过,并且始终以这种方式工作。我已经用了dbGetQuery很多,但是我不能让它们一起工作。另外,将tryCatch放入列表中确实有很大帮助。
使用dbSendQuery发送插入语句。在这种情况下,tryCatch将捕获异常:
tryCatch({
dbSendQuery(con, "insert into wrongtable values(1, 2, 3)")
},
error = function(e) print(e)
)
Run Code Online (Sandbox Code Playgroud)
对于使用dbGetQuery(我不知道为什么它失败),有一种解决方法-调用postgresqlExecStatement而postgresqlFetch不是dbGetQuery:
tryCatch({
res <- postgresqlExecStatement(con, "select * from thereisnotablewiththisname")
postgresqlFetch(res)
},
error = function(e) print(e),
warning = function(w) print(w)
)
Run Code Online (Sandbox Code Playgroud)