Closing active connections using RMySQL

Close all active connections:

dbDisconnectAll <- function(){
  ile <- length(dbListConnections(MySQL())  )
  lapply( dbListConnections(MySQL()), function(x) dbDisconnect(x) )
  cat(sprintf("%s connection(s) closed.\n", ile))
}

executing: dbDisconnectAll()


Simplest:

lapply(dbListConnections( dbDriver( drv = "MySQL")), dbDisconnect)

List all connections and disconnect them by lapply


Closing a connection

You can use dbDisconnect() together with dbListConnections() to disconnect those connections RMySQL is managing:

    all_cons <- dbListConnections(MySQL())
    for(con in all_cons) 
      dbDisconnect(con)

Check all connections have been closed

    dbListConnections(MySQL())

You could also kill any connection you're allowed to (not just those managed by RMySQL):

    dbGetQuery(mydb, "show processlist")

Where mydb is..

    mydb = dbConnect(MySQL(), user='user_id', password='password', 
                      dbname='db_name', host='host')

Close a particular connection

    dbGetQuery(mydb, "kill 2")
    dbGetQuery(mydb, "kill 5")

a. dbListConnections( dbDriver( drv = "MySQL"))

b. dbDisconnect( dbListConnections( dbDriver( drv = "MySQL"))[[index of MySQLConnection you want to close]]). To close all: lapply( dbListConnections( dbDriver( drv = "MySQL")), dbDisconnect)

Yes, you could just rewrite the table, of course you would lose all data. Or you can specify dbWriteTable(, ..., overwrite = TRUE).

I would also play with the other options, like row.names, header, field.types, quote, sep, eol. I've had a lot of weird behavior in RMySQL as well. I can't remember specifics, but it seems like I've had no error message when I had done something wrong, like forget to set row.names. HTH

Tags:

Mysql

R