将输入变量传递给Shiny R中的DBGetQyery

时间:2019-07-11 20:22:53

标签: sql r sqlite shiny

在此先感谢您的回答。我遇到的问题是我试图从Shiny应用程序中的SQLlite数据库中动态检索数据。我尝试将输入变量传递给dbGetQuery功能中的某些SQL(使用paste0)。我不断收到语法错误。我想知道是否存在将多个变量传递到SQL的好方法。我对数据库还很陌生,很聪明,谢谢您的帮助!

output$servicerplot <-renderPlotly({

filtersurve <- dbGetQuery(db, statement = 
            paste0("SELECT Year,purpose,Product,seasoning,specPool,Servicer,TPO
                  FROM ServicerScurves
                  WHERE Year =",input$ServYear,
                  "AND purpose =",input$ServPurp,
                  "AND Product =",input$ServProd,
                  "AND seasoning =",input$ServACC,
                  "AND specPool =",input$ServSpec,
                  "AND Servicer =",input$Servicers,
                  "AND TPO =",input$ServTPO))

1 个答案:

答案 0 :(得分:0)

每当从RSQLite中受支持的应用程序层(Java,Python,C#,PHP或R)调用SQL时,请考虑参数化的编程行业标准。可能的问题是,您没有正确地将字符串变量括在引号中。尽管如此,参数化避免了任何连接或标点的需要。

output$servicerplot <- renderPlotly({

   # PREPARED STATEMENT
   sql <- "SELECT Year,purpose,Product,seasoning,specPool,Servicer,TPO
           FROM ServicerScurves
           WHERE Year = ?,
             AND purpose = ?
             AND Product = ?
             AND seasoning = ?
             AND specPool = ?
             AND Servicer = ?
             AND TPO = ?"

   res <- dbSendQuery(conn, sql)

   # BIND PARAMS
   dbBind(res, list(input$ServYear, input$ServPurp, input$ServProd, input$ServACC,
                    input$ServSpec, input$Servicers, input$ServTPO))
   filtersurve <- dbFetch(res)
   dbClearResult(res)

   return(filtersurve)
})