Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute multiple SQL commands at once on R

I am using RMySQL and DBI for the connection between R and MySQL

library(RMySQL)
library(DBI, quietly = TRUE)

Everything is working fine for one command, such as

sql = "select * from clients"
con <- dbConnect(MySQL(),user=user, password=password, dbname=dbname, host=host)
rs <- dbSendQuery(con, sql)
data <- fetch(rs, n=-1)
huh <- dbHasCompleted(rs)
dbClearResult(rs)
on.exit(dbDisconnect(con))

However, when I want to execute multiple commands with ";" between them (such as to set a parameter), it returns error. For example

sql = "SET @LAST_TEN_DAY = DATE_ADD(NOW(), INTERVAL -10 DAY); select * from clients where date > @LAST_TEN_DAY"
con <- dbConnect(MySQL(),user=user, password=password, dbname=dbname, host=host)
rs <- dbSendQuery(con, sql)
data <- fetch(rs, n=-1)
huh <- dbHasCompleted(rs)
dbClearResult(rs)
on.exit(dbDisconnect(con))

Many thanks,

like image 377
Duy Bui Avatar asked Mar 15 '16 10:03

Duy Bui


1 Answers

For multiple commands we need to work as follows. The dbSendQuery will save the parameter

sql = "select * from clients where date > @LAST_TEN_DAY"
con <- dbConnect(MySQL(),user=user, password=password, dbname=dbname, host=host)
dbSendQuery(con, 'SET @LAST_TEN_DAY = DATE_ADD(NOW(), INTERVAL -10 DAY)')
rs <- dbSendQuery(con, sql)
data <- fetch(rs, n=-1)
huh <- dbHasCompleted(rs)
dbClearResult(rs)
on.exit(dbDisconnect(con))
like image 67
Duy Bui Avatar answered Sep 22 '22 05:09

Duy Bui