将以下内容更改为参数化查询条件

时间:2015-05-27 11:10:16

标签: mysql sql .net vb.net asp-classic

如何将以下更改为具有if-conditions的参数化查询...?我想将其设置为参数化查询qith命令对象...

strQry="SELECT distinct EnrolID" &_
        " FROM " & strview & " WHERE ProgramID=" &vP&_
        " AND EnrolStatus = 'ZZY' AND CampusID=" &vC


if vW <> "" THEN           
    strQry=strQry + " AND WID like '%" &WID& "%'"   
end if
    if vBID<>0 THEN 
        strQry=strQry + " AND BID=" &vBID           
    end if              
if vProgramID= "2" then 
    if vT<>0 THEN
        strQry=strQry + " AND eid=" &vT         
    end if

    if vYr<>0 THEN  
        strQry=strQry + " AND Year(A_Dt)=" &vY          
    end if       
end if
strQry = strQry + " ORDER BY EN"
set objRS=createObject("ADODB.recordset")
obj.Open strQry, Conn

1 个答案:

答案 0 :(得分:0)

首先,您的基本查询未参数化。我已修复了以下内容,但如果您的strview变量是未经过用户输入(而不是,例如,您声明的常量)那么您仍然非常容易受到SQL注入攻击。 那说:

Dim SQLCmd As New MySqlCommand

strQry="SELECT distinct EnrolID" &_
    " FROM " & strview & " WHERE ProgramID = @ProgramID" &_
    " AND EnrolStatus = 'ZZY' AND CampusID = @CampusID"

SQLCmd.Parameters.AddWithValue("@ProgramID", vP)
SQLCmd.Parameters.AddWithValue("@CampusID", vC)

If vW <> "" Then           
    strQry = strQry + " AND WID like @WID"
    SQLCmd.Parameters.AddWithValue("@WID", "%" & WID & "%")  
End If
If vBID <> 0 Then 
    strQry = strQry + " AND BID = @BID"
    SQLCmd.Parameters.AddWithValue("@BID", vBID)          
End If              
If vProgramID = "2" Then 
    If vT <> 0 Then
        strQry = strQry & " AND eid = @eID"
        SQLCmd.Parameters.AddWithValue("@eID", vT)        
    End If

    If vYr <> 0 Then  
        strQry = strQry& " AND Year(A_Dt) = @Year"
        SQLCmd.Parameters.AddWithValue("@Year", vY)         
    End If       
End If
strQry = strQry & " ORDER BY EN"
SQLCmd.CommandText = strQry