Querying an SQLite database from R

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.

Tags

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.