Querying an SQLite database from R

January 6, 2013
By

(This article was first published on Will Lowe » R, and kindly contributed to R-bloggers)

You have an SQLite database, perhaps as part of some replication materials, and you want to query it from R. You might want to be able to say:

results <- runsql("select * from mytable order by date")

and get the results back as an R object. Here's a function to do it.

In the following, I'm going to assume the database is called mydatabase.db.

First install the RSQLite package if you don't have it already. Then the following function does what's wanted:

runsql <- function(sql, dbname="mydatabase.db"){
  require(RSQLite)
  driver <- dbDriver("SQLite")
  connect <- dbConnect(driver, dbname=dbname);
  closeup <- function(){
    sqliteCloseConnection(connect)
    sqliteCloseDriver(driver)
  }
  dd <- tryCatch(dbGetQuery(connect, sql), finally=closeup)
  return(dd)
}

This code loads a driver, opens a connection, runs the query and closes the connection whether or not it is successful. If efficiency were a concern you'd want to run a bunch of queries on the same connection. All the functions you'd need for that are above.

Also, this is pretty low level interface so you may need to add types to your results

results <- transform(results, d1=as.Date(d1))

Actually dates are a little bit quirky in SQLite, but that's a post for another day.

To leave a comment for the author, please follow the link and comment on his blog: Will Lowe » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.