gpt4 book ai didi

mysql - 为搜索字符串构建 SQL 查询

转载 作者:太空宇宙 更新时间:2023-11-03 10:43:08 28 4
gpt4 key购买 nike

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

下面是我的代码:

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

任何帮助都会很棒。

最佳答案

嗯,看起来你的 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 语句而没有记录集。

关于mysql - 为搜索字符串构建 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35133590/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com