5

我尝试在 R 脚本中使用字符串变量来通过 SQL 语句使用,例如:

x="PASS"

SQL<- paste("select ID, NAME, STATUS from STUDENT where STATUS =(",x,")",sep="")
Q1 <- dbGetQuery(con, SQL)

错误说:

mysqlExecStatement(conn, statement, ...) 中的错误:
RS-DBI 驱动程序:(无法运行语句:'where 子句'中的未知列'PASS')

这意味着 STATUS =(",x,")" = PASS 并且它必须 'PASS' 并加上引号 ''

我试图把''但没有成功如下。

SQL <- paste("select ID, NAME, STATUS from STUDENT where STATUS ='(",x,")' ",sep="")
Q1 <- dbGetQuery(con, SQL)

我用数字对其进行了测试,它运行良好,但是当我使用字符串时它不起作用,因为该值必须在引号中' '

4

4 回答 4

8

改用sprintf

x <- "PASS"
sprintf("select ID, NAME, STATUS from STUDENT where STATUS = '%s'", x)

## [1] "select ID, NAME, STATUS from STUDENT where STATUS = 'PASS'"
于 2013-07-02T20:20:36.977 回答
5

尝试这个:

library(gsubfn)
x <- "PASS"

fn$dbGetQuery(con, "select ID, NAME, STATUS from STUDENT where STATUS = '$x' ")

这也有效:

s <- fn$identity("select ID, NAME, STATUS from STUDENT where STATUS = '$x' ")
dbGetQuery(con, s)
于 2013-07-02T21:31:09.423 回答
2

编辑窗口

尝试

x = "PASS"

SQL<- paste0("select ID, NAME, STATUS from STUDENT where STATUS = ", shQuote(x, 'sh'))
Q1 <- dbGetQuery(con, SQL)

更普遍shQuote的是,它对构造的东西很有用,比如:

paste0("SELECT * FROM urtable where urvar IN(", paste0(shQuote(LETTERS, 'sh'), collapse = ','), ")")
[1] "SELECT * FROM urtable where urvar IN('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z')"

 #

如果你有简单的字符串。对于更复杂的字符串,可能需要其他方法。例如,在 PoSTgreSQL 中,您可以使用Dollar-Quoted String Constants转义字符。

您没有提及您正在使用的 SQL 变体或关联的 R 包。一些 R 包可能有一些辅助函数,比如postgresqlEscapeStringsinRPostgreSQLdbEscapeStringsin RMySQL

于 2013-07-02T20:20:49.193 回答
0

使用胶水包中的glue_sql()。

x =“通过”

胶水SQL(“从学生中选择ID,名称,状态,其中STATUS = {x}”,.con = con)

在此处查看更多示例: https ://glue.tidyverse.org/#glue_sql-makes-constructing-sql-statements-safe-and-easy

于 2020-09-13T20:05:40.900 回答