Reputation: 416
I am trying to use the following function in R:
heritblup <- function(name) {
library(RMySQL)
library(DBI)
con <- dbConnect(RMySQL::MySQL(),
dbname ="mydab",
host = "localhost",
port = 3306,
user = "root",
password = "")
value1 <- 23;
rss<- paste0 ("INSERT INTO namestable
(myvalue, person)
VALUES ('$value1', '",name,"')")
rs <<- dbGetQuery (con, rss)
}
heritblup("Tommy")
But I keep getting this error:
Error in as.character.default() : no method for coercing this S4 class to a vector Called from: as.character.default()
I tried to change the paste function to this: rss<- paste0 ("INSERT INTO namestable (myvalue, person) VALUES ($value1, ",name,")")
the error persists; I have no idea whats wrong. Please help
Upvotes: 1
Views: 306
Reputation: 20085
Couple of issues in code. I'm not sure if OP is attempting to insert
records in database or fetch from database.
Assuming, based on query that he is expecting to insert data in database table.
The rule is that query should be prepared in R
the way it will be executed in MySQL. Value replacement (if any) should be performed in R
as MySQL engine will not have any idea about variables from R
.
Hence, the query preparation steps should be done as:
rss <- sprintf("INSERT INTO namestable (myvalue, person) VALUES (%d, '%s')", value1, name)
# "INSERT INTO namestable (myvalue, person) VALUES (23, 'test')"
If data insert is goal then dbGetQuery
is not right option per R documentation instead dbSendStatement()
should be used for data manipulation. The reference from help suggest:
However, callers are strongly encouraged to use dbSendStatement() for data manipulation statements.
Based on that query execution line should be:
rs <- dbSendStatement(con, rss)
ret_val <- dbGetRowsAffected(rs)
dbClearResult(rs)
dbDisconnect(con)
return(ret_val)
Upvotes: 1