How to write a parameterized SQL query?

泪湿孤枕 提交于 2019-12-25 01:25:54

问题


I am trying this query to fetch my value from a MS SQL database on basis of two conditions but still I am getting exception in the syntax part.

Can anybody tell me what is the correct way to write a parameterized query in R?

Following is the query I used:

query<- paste0("SELECT [value] FROM [RiskDashboard].[dbo].[tbl_Simulation]
                  where Row_Id=", row_id[c(1),] ," AND Script_Id=", script_id[c(1),] ,)

T_data<-sqlQuery(ch,query)

print(T_data)

回答1:


Parameterizing data is very important - especially from a security perspective. The examples you have are string concatenations and are subject to SQL injections.

The RODBCext package does have support for parameterization.

First - standard SQL parameterization syntax:

SELECT ColA, ColB FROM MyTable where FirstName = ? and LastName = ?

Each ? mark indicates in order the values that will appear in a vector. This syntax is true for ODBC regardless of platform. Others have extended to support position. eg. OLEDB supports @P1, @P2 etc.

While maybe not important for your R queries - in a multi-user system parameterized queries execute faster because the query plan is stored by the database-server (true of both Oracle and SQL Server).

To semi-plagiarize from the documentation:

library(RODBCext)
connHandle <- odbcConnect("myDatabase")
data <- sqlExecute(connHandle, "SELECT * FROM myTable WHERE column = ?", 'myValue', fetch = TRUE) 
odbcClose(connHandle)

Documentation is here: https://cran.r-project.org/web/packages/RODBCext/vignettes/Parameterized_SQL_queries.html

More discussion here: Parameterized queries with RODBC




回答2:


i got the correct way as follows:

query<- paste0("SELECT [Row_Id],[Script_id],[value] FROM 
[RiskDashboard].[dbo].      [tbl_Simulation] where Row_Id='",row_id[c(i),],"'
AND   Script_Id='",script_id[c(i),],"'")


来源:https://stackoverflow.com/questions/26754346/how-to-write-a-parameterized-sql-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!