在Shiny app中为PostgreSQL连接保持活动状态?

时间:2016-02-29 21:01:31

标签: r shiny shinydashboard rpostgresql

我有一个shiny应用,它利用RPostgreSQL连接到数据库& ad-hoc查询数据。

# Initialize environment to hold SQL parameters:
library(RPostgreSQL)
if (!exists('.sql')) .sql <- new.env()
.sql$cxn <- dbConnect(PostgreSQL(), host = "localhost", dbname = "testdb", user = "myuser", password = "Passw0rd!", port = 5432)

此代码在应用初始化时运行,但一段时间后,服务器终止连接:

> dbGetQuery(.sql$cxn, "SELECT 1")
Error in postgresqlExecStatement(conn, statement, ...) : 
  RS-DBI driver: (could not run statement: no connection to the server
)

如果我只是打电话:

.sql$cxn <- dbConnect(PostgreSQL(), host = "localhost", dbname = "testdb", user = "myuser", password = "Passw0rd!", port = 5432)
再次,它创建了第二个连接:(我想要那个)

> dbListConnections(PostgreSQL())
[[1]]
<PostgreSQLConnection:(10601,4)> 

[[2]]
<PostgreSQLConnection:(10601,5)> 

(最终,达到了最大连接数,您无法创建另一个连接:https://groups.google.com/forum/#!topic/shiny-discuss/0VjQc2a6z3M

我想创建一个连接到我的PostgreSQL数据库的函数(如果它还没有),并保持连接打开(通过SELECT'ing 1),如果它有:

getConnection <- function(.host, .user, .pw) {
  tryCatch({
    if (!exists('cxn', where = .sql)) {
      .sql$cxn <- dbConnect(PostgreSQL(), host = .host, dbname = "testdb", user = .user, password = .pw, port = 5432)
    } else {
      dbGetQuery(.sql$cxn, "SELECT 1")
    }
  }, warning = function(w) {
    NULL  # placeholder for warnings
  }, error = function(e) {
    print(e)
    cat("Looks like PostgreSQL connection died. Let's try to reconnect...\n")
    invisible(lapply(dbListConnections(PostgreSQL()), dbDisconnect))  # Close all db connections
.sql$cxn <<- dbConnect(PostgreSQL(), host = .host, dbname = "testdb", user = .user, password = .pw, port = 5432)
  }, finally = {
    return(.sql$cxn)
  })
}

getConnection(.host = "localhost", .user = "myuser", .pw = "Passw0rd!")

编辑2016/03/12:不确定原因,但我上面写的功能似乎没有正常工作......

当我打电话给我时,我得到:

> getConnection(.host = awsrds$host, .user = awsrds$username, .pw = awsrds$password)
Error in postgresqlExecStatement(conn, statement, ...) : 
  RS-DBI driver: (could not run statement: no connection to the server
)
<PostgreSQLConnection:(12495,0)> 

特别是,此部分dbGetQuery(.sql$cxn, "SELECT 1")返回:

Error in postgresqlExecStatement(conn, statement, ...) : 
  RS-DBI driver: (could not run statement: no connection to the server
)
NULL
Warning message:
In postgresqlQuickSQL(conn, statement, ...) :
  Could not create executeSELECT 1

此输出的classNULL(与错误相反?)。

任何想法我做错了什么?谢谢!

1 个答案:

答案 0 :(得分:-1)

我相信您可以通过检查连接功能来解决错误。这就是我为mysql所做的......我相信你的情况应该是一样的。关键是检查是否SELECT 1 == 'try-error'

connectionFunction <- function() {
  if (!exists("connectionName", where = .GlobalEnv)) {
      connectionName <<- dbConnect(MySQL(), default.file = mysqlconf, dbname = "dbName")
  } else if (class(try(dbGetQuery(connectionName, "SELECT 1"))) == "try-error") {
      dbDisconnect(connectionName)
      connectionName <<- dbConnect(MySQL(), default.file = mysqlconf, dbName = "dbName")
  }
  return(connectionName)

}