SQL injection in Visual Basic 2010

2019-08-30 09:29发布

I don't know how to avoid SQL injection, could someone help me with my problem?

Here is my current code:

Private Function INSERT() As String
        Dim SQLcon As New SqlConnection
        Dim SQLdr As SqlDataReader
        Try
            SQLcon.ConnectionString = "Data Source=#####;Initial Catalog=OJT;Persist Security Info=True;User ID=####;Password=#####"
            Dim SQLcmd As New SqlCommand("INSERT INTO dbo.Patients(pIDNo,pLName,pFName,pMI,pSex,pStatus,pTelNo,pDocID,pAddr,pStreet,pBarangay,pCity,pProvince,pLNameKIN,pFNameKIN,pMIKIN,pRelationKIN) VALUES('" & LabelPNumber.Text & "','" & txtLname.Text & "','" & txtFname.Text & "','" & txtMI.Text & "','" & txtPatientSex.Text & "','" & txtPatientSex.Text & "','" & txtPatientTelNo.Text & "','" & txtPatientDoctor.Text & "','" & txtStreetNumber.Text & "','" & txtStreetName.Text & "','" & txtBarangay.Text & "','" & txtCity.Text & "','" & txtProvince.Text & "','" & txtKinLname.Text & "','" & txtKinFname.Text & "','" & txtKinMI.Text & "','" & txtRelationToPatient.Text & "') ", SQLcon)
            SQLcon.Open()
            MsgBox("Patient Added!", MsgBoxStyle.Information)
            SQLdr = SQLcmd.ExecuteReader()
        Catch ex As Exception
            MessageBox.Show("Error Occured, Can't Add Patient!" & ex.Message)
        Finally
            SQLcon.Close()
        End Try
        Return "done"
    End Function

1条回答
对你真心纯属浪费
2楼-- · 2019-08-30 10:00

Basically anywhere you're concatenating strings together to create your SQL statement, especially that which comes from user input, is vulnerable.

Instead of doing this use SQL parameters, which can be added to the Parameters property of your SQL command (SQLcmd here).

I'll show you an example with one of your parameters - change your SQLCommand text to:

INSERT INTO dbo.Patients(pIDNo, ...)
VALUES(@pIDNo, ...)

Where @pIDNo is a "placeholder" in the string for the parameter value, which is sent separately from the command in the SQLParameters collection.

Then you can add a parameter with the same name as this "placeholder", and the value (it will derive the type from the value provided for you).

Here's the example from earlier:

SQLcmd.Parameters.AddWithValue("@pIDNo", LabelPNumber.Text)
查看更多
登录 后发表回答