构建搜索字符串的SQL查询

时间:2016-02-01 14:55:07

标签: mysql vb.net visual-studio

我在创建用于在数据网格视图中显示项目的搜索查询时遇到一些问题,我得到的错误是"索引超出了范围。必须是非负数且小于集合的大小。 参数名称:index"

以下是我的代码:

Try
    connect()
    Dim sql = "SELECT pcb, component, hour, faultcode, line FROM [sqlcnvfaultentry] WHERE "

    If CheckBox_pcb.Checked Then
        Sql = Sql & " and pcb = @pcb "
        cmd.Parameters.AddWithValue("@pcb", ComboBox_pcb.Text)
    End If

    If CheckBox_part.Checked Then
        Sql = Sql & " and component = @component "
        cmd.Parameters.AddWithValue("@component", ComboBox_part.Text)
    End If

    If CheckBox_hour.Checked Then
        Sql = Sql & " and hour = @hour "
        cmd.Parameters.AddWithValue("@hour", ComboBox_hour.Text)
    End If

    If CheckBox_fault.Checked Then
        Sql = Sql & " and faultcode = @faultcode "
        cmd.Parameters.AddWithValue("@faultcode", ComboBox_fault.Text)
    End If

    If CheckBox_line.Checked Then
        Sql = Sql & " and line = @line "
        cmd.Parameters.AddWithValue("@line", ComboBox_line.Text)
    End If

    Dim adapter = New SqlDataAdapter(cmd.CommandText, con.ConnectionString)
    Dim dt As New DataTable()

    cmd.CommandText = Sql
    adapter.Fill(dt)
    DataGridView_c1.DataSource = dt
    DataGridView_c1.Refresh()

    DataGridView_c1.Columns(0).HeaderText = "PCB:"
    DataGridView_c1.Columns(1).HeaderText = "Component:"
    DataGridView_c1.Columns(2).HeaderText = "Hour:"
    DataGridView_c1.Columns(3).HeaderText = "Fault Code:"
    DataGridView_c1.Columns(4).HeaderText = "Line:"

    disconnect()

Catch exp As Exception
    Throw exp
Finally

End Try

任何帮助都会很棒。

2 个答案:

答案 0 :(得分:2)

好吧,看起来你的TSQL永远不会有效。您开始使用值SELECT... WHERE的语句,然后开始向其添加所有以AND开头的内容。要解决此问题,您可以将您的语句作为SELECT... WHERE 1=1开始,然后当您开始将AND语句附加到WHERE子句时,您应该没问题。

那就是说,我不是这种构建SQL语句的方法的忠实粉丝,而是更愿意看到存储过程。

现在,关于您的实际错误:由于您的TSQL语句不有效,您的结果没有任何列,而且这部分代码......

DataGridView_c1.Columns(0).HeaderText = "PCB:"
DataGridView_c1.Columns(1).HeaderText = "Component:"
DataGridView_c1.Columns(2).HeaderText = "Hour:"
DataGridView_c1.Columns(3).HeaderText = "Fault Code:"
DataGridView_c1.Columns(4).HeaderText = "Line:"

...超出范围,因为您的无效SELECT语句没有记录集。

答案 1 :(得分:2)

在将SqlCommand.CommandText传递给SqlDataAdapter之后设置它并不会更改存储在适配器中的文本,在创建适配器之前移动SqlCommand.Commandtext的设置似乎是一个很好的修复。 ..

cmd.CommandText = Sql
Dim adapter = New SqlDataAdapter(cmd.CommandText, con.ConnectionString)
Dim dt As New DataTable()
adapter.Fill(dt)

但是,等等,你还有问题。当您将一个字符串(作为CommandText)传递给适配器构造函数时,它使用该字符串在内部构建另一个SqlCommand。此内部命令的Parameter集合为空。它不知道代码外部创建的参数集合的任何内容 因此,真正的解决方法是直接使用代码编写的SqlCommand创建适配器。

cmd.CommandText = Sql
cmd.Connection = con

' Pass the SqlCommand, it will be used to be the SelectCommand of the adapter'
Dim adapter = New SqlDataAdapter(cmd)
Dim dt As New DataTable()
' Run the SelectCommand'
adapter.Fill(dt)