我在函数中使用RPostgreSQL和sqldf,如下所示:
MyFunction <- function(Connection) {
options(sqldf.RPostgreSQL.user = Connection[1],
sqldf.RPostgreSQL.password = Connection[2],
sqldf.RPostgreSQL.dbname = Connection[3],
sqldf.RPostgreSQL.host = Connection[4],
sqldf.RPostgreSQL.port = Connection[5])
# ... some sqldf() stuff
}如何测试连接是否有效?
发布于 2013-10-21 09:52:49
一种方法是简单地尝试执行代码,并使用一条信息丰富的错误消息捕捉任何错误。请查看tryCatch的文档,以了解如何工作的详细信息。
以下博客文章介绍了基于异常的编程风格。
发布于 2013-10-21 10:40:23
可以使用isPostgresqlIdCurrent检查现有连接是否有效。
conn <- dbConnect("RPgSQL", your_database_details)
isPostgresqlIdCurrent(conn)对于测试新连接,我认为没有一种方法可以不尝试就知道连接是否有效。(在尝试连接之前,R如何知道数据库的存在和可用?)
对于大多数分析目的,只是停止一个错误和修复登录细节是最好的方法。因此,只需调用dbConnect,而不必担心额外的检查函数。
如果您正在创建某种应用程序,您需要优雅地处理错误,那么简单的tryCatch包装器就能做到这一点。
conn <- tryCatch(conn <- dbConnection(wherever), error = function(e) do_something)发布于 2013-10-21 13:40:22
我目前的设计使用tryCatch
Connection <- c('usr','secret','db','host','5432')
CheckDatabase <- function(Connection) {
require(sqldf)
require(RPostgreSQL)
options(sqldf.RPostgreSQL.user = Connection[1],
sqldf.RPostgreSQL.password = Connection[2],
sqldf.RPostgreSQL.dbname = Connection[3],
sqldf.RPostgreSQL.host = Connection[4],
sqldf.RPostgreSQL.port = Connection[5])
out <- tryCatch(
{
sqldf("select TRUE;")
},
error=function(cond) {
out <- FALSE
}
)
return(out)
}
if (!CheckDatabase(Connection)) {
stop("Not valid PostgreSQL connection.")
} else {
message("PostgreSQL connection is valid.")
}https://stackoverflow.com/questions/19489237
复制相似问题