Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to pass parameters to query in R DBI

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 * FROM table WHERE value > ?", (5,))    

Where the second parameter to the execute method is a tuple of parameters to add into the sql query

Is there a similar mechanism for R's DBI compliant APIs? The examples I've seen never show parameters passed to the query. If not, what is the safest way to interpolate in parameters to a query? I'm specifically looking at using RPostgresSQL.

like image 386
cts Avatar asked May 10 '16 07:05

cts


2 Answers

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--;")
like image 123
cts Avatar answered Nov 18 '22 22:11

cts


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.

like image 1
lrnzcig Avatar answered Nov 18 '22 23:11

lrnzcig