9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rで溜まってしまったPostgreSQLとのコネクションを全部消す

Posted at

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) 
9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?