Search code examples
rrmysql

r dbWriteTable in loop


I have many table that I am saving to a MariaDb in AWS RDS. I can manually save the tables. However I want to create a loop to do and I can't figure out the syntax on the dbWriteTable command. library(RMySQL)

dbWriteTable(con, "Account" , Account, overwrite = T)
dbWriteTable(con, "Campaign",  Campaign, overwrite = T)
dbWriteTable(con, "Contact" , Contact, overwrite = T)
dbWriteTable(con, "User", User, overwrite =T)

Instead I would like to do it in a loop.

nm = c("Account", "Campaign", "Contact",  "User")

for (i in 1:length(nm)) {

  dbWriteTable(con,  nm[i], paste(nm[i]), overwrite = TRUE)
 }

Solution

  • Per comments above, using get0 instead of paste like so will work:

    nm = c("Account", "Campaign", "Contact",  "User")
    
    for (i in 1:length(nm)) {
        dbWriteTable(con,  nm[i], get0(nm[i]), overwrite = TRUE)
    }