RでいっぱいになったPostgreSQLへのコネクションを一気に切断する方法のメモです。
下記のコードでできます。MySQLの場合は、PostgreSQL()の部分をMySQL()にすれば動くと思います。
cons <- dbListConnections(PostgreSQL()) # すべてのコネクションのリストを取得
for(con in cons){
results <- dbListResults(con) # コネクションに結びついたResultのリストを取得
if(length(results) > 0){
cat("remain\n")
for(r in results){
dbClearResult(r) # Resultの消去
}
}
dbDisconnect(con) # コネクションの切断
}
というのも、RでPostgreSQLに接続してデータを解析していると、以下のようなエラーになりがちです。
> con <- dbConnect(PostgreSQL(), host="localhost", user= "postgres", dbname="mydb")
以下にエラー postgresqlNewConnection(drv, ...) :
RS-DBI driver: (cannot allocate a new connection -- maximum of 16 connections already opened)
切断しようにも、以下のようなエラーで切断できないこともしばしば。
> dbDisconnect(con)
以下にエラー postgresqlCloseConnection(conn, ...) :
connection has pending rows (close open results set first)