Does R provide anything cleaner than tryCatch() to safely make SQL queries?
r, sql, try-catch
Solution
You might try on.exit, something like the following:
foo <- function() {
con <- dbConnect(
PostgreSQL(),
user=config$db.user,
password=config$db.password,
dbname=config$db.name,
host=config$db.host
)
on.exit({
dbDisconnect(con)
})
## ... do something w/ connection
}
When the function `foo` is about to return (or exit due to an exception), the expression passed to `on.exit` will be evaluated.
Problem
I am making SQL queries, using `tryCatch()` to prevent R from silently using up all the slots for database connections. It looks like this: ``` sql <- "SELECT * FROM addresses WHERE zipcode=10202" con <- dbConnect(PostgreSQL(), user='user', password='pswd', dbname='contacts',host='dbserv') tryCatch( { rs <- dbSendQuery(con, statement=sql) fp <- fetch(rs,n=-1) # Fetch all dbClearResult(rs) fp}, finally=dbDisconnect(con)) fp ``` Does R provide anything cleaner for the purpose? I'm thinking of how `readLines()` works with a string argument to make sure no file connection is left open.