Visual Basic 2010 中的 SQL 注入 [英] SQL injection in Visual Basic 2010
问题描述
我不知道如何避免 SQL 注入,有人可以帮我解决我的问题吗?
I don't know how to avoid SQL injection, could someone help me with my problem?
这是我当前的代码:
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
推荐答案
基本上,任何将字符串连接在一起以创建 SQL 语句的地方,尤其是来自用户输入的语句,都容易受到攻击.
Basically anywhere you're concatenating strings together to create your SQL statement, especially that which comes from user input, is vulnerable.
不要使用 SQL 参数来代替此操作,这些参数可以添加到 SQL 命令的参数属性中(此处为SQLcmd
).
Instead of doing this use SQL parameters, which can be added to the Parameters property of your SQL command (SQLcmd
here).
我将向您展示一个带有您的参数之一的示例 - 将您的 SQLCommand 文本更改为:
I'll show you an example with one of your parameters - change your SQLCommand text to:
INSERT INTO dbo.Patients(pIDNo, ...)
VALUES(@pIDNo, ...)
其中 @pIDNo
是参数值字符串中的占位符",它与 SQLParameters 集合.
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).
这是之前的例子:
SQLcmd.Parameters.AddWithValue("@pIDNo", LabelPNumber.Text)
这篇关于Visual Basic 2010 中的 SQL 注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!