如何使用 R 在 SQL 查询中执行参数替换?

How to perform parameter substitution in SQL queries using R?

编程 SQL-Python 中的特定内容我已经习惯了 总是 在执行普通 SQL 查询时使用参数替换,像这样:

# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)

# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)

psycopg2 文档中,他们甚至写道:

Never, never, NEVER use Python string concatenation (+) or string parameters interpolation (%) to pass variables to a SQL query string. Not even at gunpoint.

现在我必须将数据从 R 保存到 SQLite 数据库中。我尝试使用仅接受两个参数的函数 dbSendQuery 来执行此操作:连接处理程序和查询本身。但是如何提供替换参数呢?!

谷歌搜索我发现(令人惊讶的是!)在 R 社区中,人们总是建议使用 paste 构建一个 SQL 查询,然后将其提供给 dbSendQuery。但是安全和优雅呢?好像没人关心。。。我个人不太明白。

使用 RSQLite,您可以使用 dbGetPreparedQuery 进行参数化查询(即,将值绑定到准备好的语句)。参见 docs。但是,您必须将绑定值作为数据框对象传递:

sql <- "SELECT * FROM stocks WHERE symbol=?"

t <- 'RHAT'
df <- dbGetPreparedQuery(con, sql, bind.data=data.frame(symbol=t))