Proper way to pass parameters to query in R DBI

后端 未结 2 371
闹比i
闹比i 2020-12-16 21:41

In perl/python DBI APIs have a mechanism to safely interpolate in parameters to an sql query. For example in python I would do:

cursor.execute(\"SELECT * FR         


        
相关标签:
2条回答
  • 2020-12-16 22:13

    Just for completeness, I'll add an answer based on Hadley's comment. The DBI package now has the function sqlInterpolate which can also perform this. It requires a list of function arguments to be named in the sql query that all must start with a ?. Excerpt from the DBI manual below

    sql <- "SELECT * FROM X WHERE name = ?name"
    sqlInterpolate(ANSI(), sql, name = "Hadley")
    # This is safe because the single quote has been double escaped
    sqlInterpolate(ANSI(), sql, name = "H'); DROP TABLE--;")
    
    0 讨论(0)
  • 2020-12-16 22:26

    Indeed the use of bind variables is not really well documented. Anyway the ODBC commands in R work differently for different databases. One possibility for postgres would be like this:

    res <- postgresqlExecStatement(con, "SELECT * FROM table WHERE value > $1", c(5))
    postgresqlFetch(res)
    postgresqlCloseResult(res)
    

    Hope it helps.

    0 讨论(0)
提交回复
热议问题