【问题标题】:Pass string variable in R script to use it in SQL statement在 R 脚本中传递字符串变量以在 SQL 语句中使用它
【发布时间】:2013-07-02 20:16:43
【问题描述】:

我尝试在 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)

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

【问题讨论】:

    标签: sql r variables


    【解决方案1】:

    改用sprintf

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

    【讨论】:

    • 感谢 dickoa 我尝试使用 sprintf 但它不起作用,在我的情况下,我使用其他包含整数的变量类型。我的情况的更新是:x="PASS" Y=1100 SQL
    【解决方案2】:

    试试这个:

    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)
    

    【讨论】:

    • 感谢 G. Grothendieck,我试过了,它适用于不同类型的变量。我还要感谢所有回复的人。。
    【解决方案3】:

    编辑窗口

    试试

    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 包可能具有辅助函数,例如 RPostgreSQL 中的 postgresqlEscapeStringsRMySQL 中的 dbEscapeStrings

    【讨论】:

    • 括号可以保留也可以去掉。
    • 这似乎是对shQuote 的误用,它用于引用OS shell 的字符串。不能保证相同的引号是数据库所期望的。
    【解决方案4】:

    使用glue包中的glue_sql()。

    x = "通过"

    glue_sql("select ID, NAME, STATUS from STUDENT where STATUS = {x}", .con = con)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-07
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 2023-03-25
      • 2010-12-27
      • 2022-06-29
      • 2014-10-09
      相关资源
      最近更新 更多