Connect to database from within a function

I am trying to connect to an ODBC database that's a defined DSN from within a function.

(To ultimate goal is to standardize the DB connection process within our team and log information about connections to an in-house log file.)

I thought this would be easy, but I'm having trouble getting it to work. (So now I'm stuck wanting to understand why!)

I've tried different variations, but I am trying something like this:

connectDB <- function() {
  con <- DBI::dbConnect(odbc::odbc(), "MyDB")
  
  assign("MyDB", con, envir = .GlobalEnv)

}

However, no matter what I try, it just creates a variable, not a connection. (I realize this is what "assign" does -- creates a variable; I saw a thread on stack exchange that said this would work. I have tried ways: open() -- since this needs to be a connection, and I've even tried using .valueClassTest() -- though I don't know enough to use this effectively.)

Any insight or help is appreciated.

This let's con in the global environment and it can be used to query the databse (as long as con is a valid connection).

connectDB <- function() {
    con <<- DBI::dbConnect(odbc::odbc(), "MyDB")
}

This works, but the assign() method from above actually works as well.

My mistake was expecting this to show up the same way in the Connections tab in RStudio, but it does not for reasons explained here:

https://rstudio.github.io/rstudio-extensions/connections-contract.html

In other words, it's not so much that it wasn't working. more that it looked different than I expected.

I'm still experimenting, but it does appear to work either with your <<- method or the assign() method.

Thanks

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.