简体   繁体   中英

R user-defined function to import ACCESS table via ODBC

this might be something simple, but I couldn't figure out a viable solution.

My setup is:

    R version 3.3.1 (2016-06-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

locale:
[1] LC_COLLATE=Portuguese_Brazil.1252  LC_CTYPE=Portuguese_Brazil.1252    LC_MONETARY=Portuguese_Brazil.1252 LC_NUMERIC=C                      
[5] LC_TIME=Portuguese_Brazil.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] tools_3.3.1  rpart_4.1-10

I'm building a function to import files from ACCESS DB via ODBC as folow:

importa.sql <- function(someFile)
  {
    library(RODBC) 
    con <- odbcConnect("someTable") 
    qry<-paste("(","SELECT * FROM ",someFile,")")
    someFile <- sqlQuery(con,qry,stringsAsFactors=FALSE) 
  }

I've tested each line and the code is working as expected. The problem is: when I run the function, it seems to work perfectly, but there's no file imported!!!

Does anyone could help me?

Your function return NULL because the last statement of the function ir assignment to the local object someFile . It would be good to close the connection. Try this function.

importa.sql <- function(someFile) {
  library(RODBC) 
  con <- odbcConnect("someTable") 
  qry <- paste("(", "SELECT * FROM ", someFile, ")")
  df <- sqlQuery(con, qry, stringsAsFactors = FALSE)
  close(con)
  return(df)
}

In case of someone has the same doubt, the solution is really really simple.

Just call the function this way:

file <- importa.sql(someFile)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM