0

我有一个包含 SQL 查询的程序,昨天有人向我指出它很容易受到 SQL 注入攻击。在做了一些研究之后,我可以看到要解决这个问题,我需要使用参数来代替。我有以下代码...如何参数化?

Public Shared Function SaveNewPerson(ByVal firstName As String, lastName As String, ByVal age As Integer, ByVal postcode As String, m_cn As OleDbConnection)

    Dim tr As OleDbTransaction = Nothing

    Try
        tr = m_cn.BeginTransaction()

        Dim Dc As New OleDbCommand
        Dc.Connection = m_cn

        Dc.CommandText = "INSERT INTO tblPerson([firstName], [lastName], [age], [postcode]) VALUES('" & firstName & "', '" & lastName & "', '" & age & "', '" & postcode & "')"
        Dc.Transaction = tr
        Dc.ExecuteNonQuery()

        Dim personID As Integer

        Dc.CommandText = "SELECT SCOPE_IDENTITY() AS personID"
        Dc.CommandType = CommandType.Text
        personID = CType(Dc.ExecuteScalar(), Integer)

        tr.Commit()

    Catch ex As Exception

        tr.Rollback()

        Throw
    End Try

End Function
4

2 回答 2

0

我会先创建一个存储过程插入到 sql server 然后使用

    dc.commandText = "Your stored procedure name"
    dc.commandType = CommandType.StoredProcedure
    Dim myParam as oledb.OleDbParameter = dc.parameters.add("@personID", oledbtype.int)
    myParam.Direction = ParameterDirection.ReturnValue
    dc.Parameters.Add("@firstName", OleDbType.VarChar).Value = [firstname]
    ....
    ....

    Dim returnId as Integer = Cint(dc.Parameters("@personID").Value)   
于 2016-07-19T10:09:30.370 回答
-1
   Dc.CommandText = "INSERT INTO tblPerson([firstName], [lastName], [age], [postcode]) VALUES('" & firstName & "', '" & lastName & "', '" & age & "', '" & postcode & "')"

将此更改为

Dc.CommandText = "INSERT INTO tblPerson([firstName], [lastName], [age], [postcode]) VALUES(?, ?, ?, ?)"
Dc.Parameters.Add("@first", OleDbType.VarChar, firstName)
Dc.Parameters.Add("@last", OleDbType.VarChar, lastName)
Dc.Parameters.Add("@age", OleDbType.Integer, age)
Dc.Parameters.Add("@postcode", OleDbType.VarChar, postcode )

(检查OldDbType是否通过了正确的值。)

注意。参数集合中的顺序决定了哪个参数匹配哪个?占位符。给参数的名称(似乎)被忽略了。

于 2016-07-19T09:56:07.607 回答