在R上一次执行多个SQL命令

时间:2016-03-15 10:49:26

标签: mysql sql r rmysql r-dbi

我正在使用RMySQL和DBI来连接R和MySQL之间的连接

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

对于一个命令,一切都正常,例如

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))

然而,当我想用​​&#34 ;;&#34;执行多个命令时它们之间(例如设置参数),它返回错误。例如

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))

非常感谢,

1 个答案:

答案 0 :(得分:8)

对于多个命令,我们需要按如下方式工作。 dbSendQuery将保存参数

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))
相关问题