首页 > 解决方案 > vb.net sql select语句查找所有Not Null的,我需要使用参数吗?

问题描述

我只是想在我的 SQL 数据库表中查找所有不等于 null 的记录。因此,当我编写 select 语句时,我会像对待其他任何事情一样对待它,以避免 sql 注入问题。

这是一个例子:

Command = New SqlCommand
connection.Open()
Command.Connection = connection
Command.CommandType = CommandType.Text
Command.CommandText = "SELECT * FROM MyTable WHERE [Comments] IS NOT NULL" 'Have tried [Comments]=@Comments
'Command.Parameters.AddWithValue("@Comments", "IS NOT NULL")
da = New SqlDataAdapter(Command)
da.Fill(ds, "MyTable")
For Each roww As DataRow In ds.Tables("MyTable").Rows
    If (Not IsDBNull(roww("Comments"))) Then
        IDLIST.Add(roww("TempID"))
        Comments_RichText.AppendText("Date of Service: " & roww("FromDate") & " | " & roww("Name") & vbNewLine & roww("Comments") & vbNewLine & vbNewLine)
    End If
Next
connection.close

如您所见,我已经尝试使用参数来避免 SQL 注入(但不返回任何内容)和没有返回正确行的参数。为什么参数方式不起作用?由于我没有在语句中连接任何内容,例如 TextBox.Text 或字符串,我是否必须使用参数 for IS NOT NULL?任何帮助都会很棒,因为我不明白为什么一种方式有效而另一种方式无效。

标签: mysqlvb.netparameter-passing

解决方案


参数化将不起作用,因为这将使用相等运算符进行检查,这不适用于IS NOT NULL. 它不像你想的那样工作(它不只是用你的参数重写字符串)。

不过,这仍然很容易实现,使用空合并,例如:

 SELECT * FROM MyTable WHERE ISNULL([Comments].'Empty') != @Comments

@Comments你想找到空的时,如果你明白我的意思,那就是“空”。您显然可以使用任何您想要的字符串变量来代替'Empty'.


推荐阅读