Querying an SQLite database from R
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.