我无法弄清楚如何扩展我的代码

时间:2014-11-18 05:11:12

标签: sql-server vb.net visual-studio-2010 visual-studio sql-server-2008

我需要过滤数据库中的数据。使用文本框。 在我的申请中。我使用4个文本框(用户,PC,IP和资产)。我想使用这些框来过滤数据,如果它已经存在于我的数据库中。 我有这个代码工作,但它只适用于一个文本框。 你能帮我扩展这段代码吗?所以我能够使用所有4个文本框过滤我的所有数据?

SQL.RunQuery("SELECT * FROM members WHERE members.User = '" & txtUser.Text & "'")
    If SQL.SQLDataset.Tables(0).Rows.Count > 0 Then
        MsgBox("already exists!")
        Exit Sub
    Else

提前感谢。

1 个答案:

答案 0 :(得分:1)

你可以这样做:

Dim stmt As String = "SELECT * FROM members WHERE members.User = '" & txtUser.Text & "'"

if Not txtPC.text.trim.length = 0 then
    stmt = stmt & " AND members.PC = '" & txtPC.Text & "'"
End If
if Not txtIP.text.trim.length = 0 then
    stmt = stmt & " AND members.IP = '" & txtIP.Text & "'"
End If
if Not txtAsset.text.trim.length = 0 then
    stmt = stmt & " AND members.Asset = '" & txtAsset.Text & "'"
End If

SQL.RunQuery(stmt)
If SQL.SQLDataset.Tables(0).Rows.Count > 0 Then
    MsgBox("already exists!")
    Exit Sub
Else
    ....
End If

但我严格建议您使用SqlCommand.Prepare Method,因为您当前的查询已向Sql Injection公开