Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does R provide anything cleaner than tryCatch() to safely make SQL queries?

Tags:

sql

r

try-catch

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.

like image 238
Brian B Avatar asked Dec 30 '25 09:12

Brian B


1 Answers

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.

like image 65
cbare Avatar answered Jan 02 '26 00:01

cbare