编程构建SQL查询R/SHINY/RODBC



我正在使用r/shiny中的inputDaterange()构建一个SQL查询语句。我的问题是处理各种字符串以将日期包括到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 服务器]不正确的语法"。[RODBC]错误:无法 sqlexectirect'Select [Sensor_name],[温度] [dbo]。[温度_sensor] network_id ='24162'和date> ‘18 -09-2017'和date&lt;‘22 -09-2017''

我需要用" select"中的"启动"字符串关闭字符串。...,我尝试将"""或dquote(")添加到confenate"中,但我仍然遇到错误。<<<<<<<<<<<</p>

高度赞赏任何建议?

我建议使用 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注入。

最新更新