Visual Basic 2010中的SQL注入

时间:2013-02-02 10:40:23

标签: vb.net sql-server-2008 sql-server-2005 sql-injection

我不知道如何避免SQL注入,有人可以帮我解决我的问题吗?

这是我目前的代码:

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 个答案:

答案 0 :(得分:4)

基本上,在将字符串连接在一起以创建SQL语句的任何地方,特别是来自用户输入的语句,都是易受攻击的。

而不是这样做,而是使用SQL参数,这些参数可以添加到SQL命令的Parameters属性中(SQLcmd这里)。

我将向您展示一个带有您参数的示例 - 将您的SQLCommand文本更改为:

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

其中@pIDNo是参数值字符串中的“占位符”,与SQLParameters collection中的命令分开发送。

然后你可以添加一个与这个“占位符”同名的参数和值(它将从为你提供的值中派生出类型)。

这是前面的例子:

SQLcmd.Parameters.AddWithValue("@pIDNo", LabelPNumber.Text)