Vb.net 为网页获取价值-重写代码以避免sql注入
我正试图重写代码,以防止SQL注入漏洞。我看到了用于插入或更新表的代码,但不仅仅是用于获取值。以下是易受攻击的代码:Vb.net 为网页获取价值-重写代码以避免sql注入,vb.net,parameters,Vb.net,Parameters,我正试图重写代码,以防止SQL注入漏洞。我看到了用于插入或更新表的代码,但不仅仅是用于获取值。以下是易受攻击的代码: 'Get network login name (name only) split = windowsLoginName.Split("\".ToCharArray) vname = split(1) 'Get employeeid from table that matches login name cmde.CommandText = "
'Get network login name (name only)
split = windowsLoginName.Split("\".ToCharArray)
vname = split(1)
'Get employeeid from table that matches login name
cmde.CommandText = "SELECT EmployeeID FROM tblEmployees where login = '" & vname & "'"
cmde.CommandType = CommandType.Text
cmde.Connection = sqlConnection
sqlConnection.Open()
'employeeid
rve = cmde.ExecuteScalar()
sqlConnection.Close()
我开始重写代码,到目前为止我已经做到了:
sql1 = "Select EmployeeID from tblEmployees where login = @loginname"
cmde = new sqlcommand(sql1)
这就是我被困的地方:
cmde.parameters.????("@loginname", vname)
cmde.ExecuteReader()
我不是在添加、更新或插入-我只是希望该值出现在我的网页上。代码是什么?代码的其余部分正确吗?提前谢谢
****继续。。。
在得到帮助后,我产生了这段代码,但得到了一个错误-ExecuteReader:Connection属性尚未初始化。我很困惑。代码如下:
Dim windowsLoginName As System.String = HttpContext.Current.User.Identity.Name 'System.Security.Principal.WindowsIdentity.GetCurrent().Name
Dim split As String() = Nothing
Dim vname As String
Dim sqlConnection As New SqlConnection("Data Source=WillSQL\ict2;Initial Catalog=TimeSQL;Integrated Security=SSPI")
Dim sqlemp As String
Dim cmde As New SqlCommand
Dim rve As Object
'Get network login name (name only)
split = windowsLoginName.Split("\".ToCharArray)
vname = split(1)
'Get employeeid from table that matches login name
sqlConnection.Open()
sqlemp = "SELECT EmployeeID FROM tblEmployees where login = @loginname"
cmde = New SqlCommand(sqlemp)
cmde.Parameters.AddWithValue("@loginname", vname)
rve = cmde.ExecuteReader()
sqlConnection.Close()
嗯?您正在添加一个参数。这与使用parameters.cmde.parameters的任何其他代码没有区别。AddWithValue@loginname,vname应该可以。谢谢Norbert!现在,我得到一个错误-ExecuteReader:Connection属性尚未初始化。我会编辑帖子,这样你就可以看到代码了;上的示例显示了一种简单的方法。此外,您可能希望避免在代码中使用与类名sqlConnection相同的变量名,因为这可能会使调试某些事情变得笨拙。P.P.S.AddWithValue总有一天会回来咬你的,更可靠的方法是使用类似于.AddNew SqlParameter和{.ParameterName=@loginname、.SqlDbType=SqlDbType.NVarChar、.Value=vname}的东西。谢谢Andrew!我想我有进展了。我正在打开一个与此相关的新帖子。