【问题标题】:Check that connection is valid检查连接是否有效
【发布时间】:2013-10-29 15:11:57
【问题描述】:

我在我的函数中使用RPostgreSQLsqldf,如下所示:

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
}

如何测试连接是否有效?

【问题讨论】:

    标签: r sqldf rpostgresql


    【解决方案1】:

    一种方法是简单地尝试执行代码,并使用信息丰富的错误消息捕获任何错误。查看tryCatch 的文档以了解有关其工作原理的详细信息。

    following blog 帖子介绍了基于异常的编程风格。

    【讨论】:

      【解决方案2】:

      您可以使用isPostgresqlIdCurrent 检查现有连接是否有效。

      conn <- dbConnect("RPgSQL", your_database_details)
      isPostgresqlIdCurrent(conn)
      

      对于测试新连接,我认为没有办法不尝试就知道连接是否有效。 (在尝试连接之前,R 如何知道数据库存在并且可用?)

      对于大多数分析目的,最好的方法是停止错误并修复登录详细信息。所以只需拨打dbConnect,不用担心额外的检查功能。

      如果您正在创建某种需要优雅地处理错误的应用程序,一个简单的tryCatch 包装器应该可以解决问题。

      conn <- tryCatch(conn <- dbConnection(wherever), error = function(e) do_something)
      

      【讨论】:

      • 使用conn &lt;- dbConnect("PostgreSQL", host="localhost",port=5432,dbname='db',user='usr',password='secret')会立即返回错误。
      • 哦,我明白了。这个问题模棱两可。您想在连接之前检查连接。我以为您想检查现有连接是否仍然有效。
      • 最好使用标准泛型dbIsValid(),RPostgreSQL 不支持,但 RPostgres 支持
      • dbIsValid 似乎在检查语法,但实际上并未尝试连接数据库。
      【解决方案3】:

      我目前的设计使用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.")
      }
      

      【讨论】:

      • 你应该使用library()而不是require()(所以如果包不可用会抛出错误),它们应该在顶层,而不是在函数内
      • 或更好,if(!require("pkg", quietly=TRUE)) stop("own error msg")
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-30
      • 1970-01-01
      • 2020-11-19
      • 2019-04-04
      • 1970-01-01
      • 2015-10-25
      相关资源
      最近更新 更多