Search code examples
r

How can I use a character containing the DB instead of the connectin in R?


I have a database like this

library(RSQLite)
test <- dbConnect(RSQLite::SQLite(), "")
dbWriteTable(test, "mtcars", mtcars)

char_string <- "test"

How can I use the char_string with dbListTables to see the tables in the database?


Solution

  • If char_string (con_name in the function) contains the name of the variable holding the connection then use get as shown.

    It needs to know which environment to look into to find the char_string so also provide an envir argument. The default used here is likely what is needed in most cases so can normally be omitted in the call.

    ListTables  <- function(con_name, envir = parent.frame()) {
      con <- get(con_name, envir)
      dbListTables(con) 
    }
    
    
    # test
    library(RSQLite)
    test <- dbConnect(SQLite())
    dbWriteTable(test, "mtcars", mtcars)
    char_string <- "test"
    
    ListTables(char_string)
    ## [1] "mtcars"