【问题标题】:R - Can I pass a command line argument using Rscript to a query using RMySQL dbConnect?R - 我可以将使用 Rscript 的命令行参数传递给使用 RMySQL dbConnect 的查询吗?
【发布时间】:2014-12-22 21:17:57
【问题描述】:

我正在尝试将站点 id 参数作为整数从命令行上的 Rscript 传递到使用 RMySQL 的 dbConnect 内的 SQL 语句。但是我收到一个错误 “mysqlQuickSQL(conn, statement, ...) 中的错误: 未使用的参数 ("3", " AND name = 'HVAC #1 Supply Temp' ORDER BY created DESC LIMIT 15;")"

user@debian:~$ Rscript deltaTsql.R 3

是我从命令提示符运行的。

我的脚本是

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

args <- commandArgs(TRUE)
print(length(args))
as.integer(args[1])

con <- dbConnect(MySQL(), user="user", password="password", dbname="dbname", host="host")

r1.dat <- dbGetQuery(con, "SELECT `site_id`,`name`,`value`,`created` FROM `table` WHERE `site_id` = ", args[1], " AND `name` = 'HVAC #1 Supply Temp' ORDER BY `created` DESC LIMIT 15;")
r2.dat <- dbGetQuery(con, "SELECT `site_id`,`name`,`value`,`created` FROM `table` WHERE `site_id` =", args[1], " AND `name` = 'HVAC #1 Return Temp' ORDER BY `created` DESC LIMIT 15;")

r <- merge(r1.dat,r2.dat,by=c("created","site_id"))

r$supplytemp <- (r$value.x*(9/5)+32)
r$returntemp <- (r$value.y*(9/5)+32)

r$deltaT <- (r$returntemp-r$supplytemp)
deltaT <- r$deltaT

deltaTcheck <- function(deltaT) {
if (deltaT>25) {
return(1)
}
else if (deltaT<10) {
return(-1)
}
else {
return(0)
}
}

deltaTout <- vapply(deltaT, deltaTcheck, numeric(1))
deltaTjson <- toJSON(deltaTout)
deltaTjson

我希望能够将相同的参数传递给两个单独的 SQL 语句,以便在将它们合并到站点 ID 之前分别获取它们。任何帮助或反馈将不胜感激。谢谢

【问题讨论】:

    标签: r rmysql rscript


    【解决方案1】:

    你需要把你的SQL语句paste()组合成一个单一的字符值

    r1.dat <- dbGetQuery(con, paste0("SELECT `site_id`,`name`,`value`,`created` 
        FROM `table` 
        WHERE `site_id` = ", args[1], " AND `name` = 'HVAC #1 Supply Temp' 
        ORDER BY `created` DESC LIMIT 15;"))
    

    【讨论】:

    • 使用参数化查询会更安全
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 2012-01-01
    • 2012-02-07
    • 1970-01-01
    相关资源
    最近更新 更多