我想弄清楚如何比较两个字符串值的绝对匹配。 IE。 “abc”<>“abc”。
“Abc”在 SQL(Usr) 中位于一行,“abc”是变量值。
当我运行此命令时 - “从 UserTable 中选择 Count(*),其中 UserName = '" & Usr & "'" & " 和密码 = '" & Pwd & "'" - 它告诉我这两个值是相同的。
我不知道如何进行绝对比较??
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Usr As String, Pwd As String
Usr = TextBox1.Text.Trim
Pwd = TextBox2.Text.Trim
Dim i As Integer
user_stmt = "Select Count(*) from UserTable where UserName = '" & Usr & "'" & " and Password = '" & Pwd & "'"
User_Cmd = New SqlCommand(user_stmt, con)
con.Open()
i = User_Cmd.ExecuteScalar()
Stop
If i = 1 Then
MsgBox("Found")
Else
MsgBox("Exit")
End If
End Sub
谢谢,
迈克
代码中有几件非常重要的事情需要考虑和纠正:
SQL注入风险:
您的代码容易受到 SQL 注入攻击。切勿将字符串值直接连接到 SQL 语句中。请改用参数化查询。
SQL 中的大小写敏感性:
如果您想要区分大小写的比较,则需要通过在比较中附加 COLLATE Latin1_General_BIN 来强制进行二进制比较。
存储密码:
不要在数据库中存储纯文本密码。始终存储密码的加盐哈希值并比较哈希值。 明文密码存储存在严重的安全风险。
这是您问题的潜在解决方案:(无需使用盐进行哈希处理,但您可以轻松找到为您执行此操作的函数)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Usr As String, Pwd As String
Usr = TextBox1.Text.Trim
Pwd = TextBox2.Text.Trim
Dim i As Integer
user_stmt = "SELECT Count(*) FROM UserTable WHERE UserName COLLATE Latin1_General_CS_AS = @UserName AND Password COLLATE Latin1_General_CS_AS = @Password"
User_Cmd = New SqlCommand(user_stmt, con)
User_Cmd.Parameters.AddWithValue("@UserName", Usr)
User_Cmd.Parameters.AddWithValue("@Password", Pwd)
con.Open()
i = User_Cmd.ExecuteScalar()
con.Close()
If i = 1 Then
MsgBox("Found")
Else
MsgBox("Exit")
End If
End Sub