0

Im having a dataframe that looks like this:

city <- c("Alkmaar", "Den Haag")
df <- data.frame(city)

What I would like to do now is write values into a mysql database. Therefore I do the following:

 library(DBI)
 con <- dbConnect(RMySQL::MySQL(),
                dbname = "match_predictions",
                host = "109.237.221.34",
                port = 3306,
                user = "**",
                password = "***")


 for(i in 1:nrow(df)){
  var1 <- city[i]
 dbGetQuery(con, "INSERT INTO weather(city) VALUES(var1)")
 }

But this trows an error:

  Error in .local(conn, statement, ...) : 
  could not run statement: Unknown column 'var1' in 'field list' 

Any thoughts on how i can insert a variable into the database?

3
  • You can use something like sprintf("INSERT INTO weather(city) VALUES(%s)", var1). If var1 is a vector of cities, a vector of queries will be returned (one for each city). Commented Feb 22, 2016 at 16:04
  • Thanks @steveb but if I run: example <- dbSendQuery(con, sprintf("INSERT INTO weather(city) VALUES(%s)", x)) I still get the error: Error in .local(conn, statement, ...) : could not run statement: Unknown column 'h' in 'field list'. (this of course with h defined as variable Commented Feb 22, 2016 at 16:06
  • It worked for me, I was able to build the string "INSERT INTO weather(city) VALUES(Alkmaar)". In your case, I don't know what x is. Commented Feb 22, 2016 at 16:11

3 Answers 3

1

Just use paste0 to write the query for each city. I added in the single quotes and then you just need to make sure that you escape any single quotes in the city names if that occurs.

for(i in 1:nrow(df)){
  var1 <- city[i]
  # excape single quotes
  var2 <- gsub("\\'", "\\'\\'", var1)
  dbGetQuery(con, paste0("INSERT INTO weather(city) VALUES('", var2, "')"))
}
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! I am glad that it worked. I run into this all the time hence the added attention to the single quotes :)
0

try this:

library(DBI)
 con <- dbConnect(RMySQL::MySQL(),
                dbname = "match_predictions",
                host = "109.237.221.34",
                port = 3306,
                user = "**",
                password = "***")


 for(i in 1:nrow(df)){
  var1 <- city[i]
 dbGetQuery(con, cat("INSERT INTO weather(city) VALUES(", var1 <- city[i], ")"))
 }

Comments

0

Try replacing the dbGetQuery line in your code with the dbGetQuery line shown here:

library(gsubfn)

fn$dbGetQuery(con, "INSERT INTO weather(city) VALUES('$var1')")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.