tags:

views:

48

answers:

1
+1  Q: 

RODBC Insert Query

This is my first attempt to throw data back and forth between a local MySQL database and R. That said, I have a table created in the database and want to insert data into it. Currently, it is a blank table (created with MySQL Query Browser) and has a PK set.

I am using the RODBC package (RMySQL gives me errors) and prefer to stick with this library.

How should I go about inserting the data from a data frame into this table? Is there a quick solution or do I need to:

  1. Create a new temp table from my dataframe
  2. Insert the data
  3. Drop the temp table

With separate commands? Any help much appreciated!

+2  A: 

See help(sqlSave) in the package documentation; the example shows

channel <- odbcConnect("test")  
sqlSave(channel, USArrests, rownames = "state", addPK=TRUE)   
sqlFetch(channel, "USArrests", rownames = "state") # get the lot
foo <- cbind(state=row.names(USArrests), USArrests)[1:3, c(1,3)]  
foo[1,2] <- 222   
sqlUpdate(channel, foo, "USArrests")   
sqlFetch(channel, "USArrests", rownames = "state", max = 5)  
sqlDrop(channel, "USArrests")  
close(channel) 

which hopefully should be enough to get you going.

Dirk Eddelbuettel