Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert data table into SQLite table using RSQLite?

Tags:

sqlite

r

rsqlite

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?

like image 761
J0HN_TIT0R Avatar asked Apr 07 '26 22:04

J0HN_TIT0R


1 Answers

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

like image 121
Eric Watt Avatar answered Apr 10 '26 16:04

Eric Watt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!