3

I am very comfortable using R, but I've never used RSQLite or even SQLite, so I have a question on how to best use RSQLite to add data from a data frame in R to an SQLite table.

I understand that I can create tables and add data like so:

db <- dbConnect(SQLite(), dbname="Test.sqlite")

dbSendQuery(conn = db,  "CREATE TABLE School (SchID INTEGER,
        Location TEXT, Authority TEXT, SchSize TEXT)")

dbSendQuery(conn = db,
            "INSERT INTO School
         VALUES (1, 'urban', 'state', 'medium')")
dbSendQuery(conn = db,
            "INSERT INTO School
         VALUES (2, 'urban', 'independent', 'large')")
dbSendQuery(conn = db,
            "INSERT INTO School
         VALUES (3, 'rural', 'state', 'small')")

However, to do multiple INSERT statements like this, I'd need to parse all rows of the data frame using a for loop. Is it possible to use vectors and a single INSERT to populate the SQLite table with all values from a data frame?

J0HN_TIT0R
  • 323
  • 1
  • 13

1 Answers1

7

You can use dbWriteTable to write the table in one go. Read the vignette to see more examples.

Eric Watt
  • 3,180
  • 9
  • 21