R与连接池

你能想到的,往往都有人帮你实现了,比如R下数据库连接池的问题,答案也是肯定的,而且是由大名顶顶RStudio来实现的,Object Pooling in R

这货不仅仅是数据库连接池,只是目前仅支持DBI罢了。

#devtools::install_github("rstudio/pool")
library(pool)
pool <- dbPool(
  drv = RMySQL::MySQL(),
  dbname = "shinydemo",
  host = "shiny-demo.csa7qlmguqrf.us-east-1.rds.amazonaws.com",
  username = "guest",
  password = "guest"
)

dbGetQuery(pool, "SELECT * FROM City LIMIT 5;")


conn <- poolCheckout(pool)
rs <- dbSendQuery(conn, "SELECT * FROM City LIMIT 5;")
if (dbGetInfo(rs, what = "rowCount") > 5) {
  warning("dubious result -- rolling back transaction")
  dbRollback(conn)
}
poolReturn(conn)  ## alternatively, use: dbDisconnect(conn)