以编程方式构建SQL查询R / Shiny / RODBC

时间:2017-09-22 16:32:59

标签: r string shiny double-quotes single-quotes

我在R / Shiny中使用inputDateRange()构建SQL Query语句。我的问题是处理各种字符串以将日期包含在SQL的WHERE条件中:

这是我的代码:

t.query <- paste0("Select [sensor_name], [temperature] from [dbo].
[temperature_sensor] where network_id = '24162' and date > "
, sQuote(format(input$my.dateRange[1], format="%d-%m-%Y"))  
, " and date < "
, sQuote(format(input$my.dateRange[2], format="%d-%m-%Y"))
)

现在语句以单引号结束,我收到以下错误:

  

42000 102 [Microsoft] [SQL Server的ODBC驱动程序13] [SQL   服务器]&#39;'&#39;附近的语法不正确。 [RODBC]错误:不能   SQLExecDirect&#39;选择[sensor_name],[温度]   [dbo]。[temperature_sensor]其中network_id =&#39; 24162&#39;和日期&gt;   '18 -09-2017'和日期&lt; '22 -09-2017’ &#39;

我需要用&#34;关闭字符串。当我开始在&#34;选择....时,我试图明确地添加&#34;&#34;&#34;或者dQuote(&#34;&#34;)连接&#34;但我仍然遇到错误。

高度赞赏任何建议?

1 个答案:

答案 0 :(得分:0)

我建议使用RODBCext,这样您就可以将查询参数化为

library(RODBCext)
channel <- odbcConnect(...) # make your connection object here
Data <- 
  sqlExecute(channel = channel,
             query = "Select [sensor_name], [temperature] 
                      from [dbo].[temperature_sensor] 
                      where network_id = ? and date between ? and ?",
             data = list('24162',
                         format(input$my.dateRange[1], 
                                format = "%Y-%m-%d"),
                         format(input$my.dateRange[2],
                                format = "%Y-%m-%d")),
             fetch = TRUE,
             stringsAsFactors = FALSE)

这种方法有很多优点,包括消除匹配引号的挫败感(由于下一个原因你不应该这样做),并保护你的数据免受SQL注入。