0

我正在尝试在单个按钮上构建一个功能,以根据在多个组合框中进行的选择来搜索我的数据库。我有四个组合框,可以为空或有值。我的最终结果应该是能够通过增强组合框来过滤数据网格视图,从而获得动态和连接的查询。

Private Sub Button10_Click_1(sender As Object, e As EventArgs) Handles Button10.Click
Dim conn As New 

FbConnection("User=SYSDBA;Password=masterkey;Database=..\DB.gdb;DataSource=localhost;Port=3050;Dialect=3;Charset=NONE;Role=;Connection lifetime=15;Pooling=true;MinPoolSize=0;MaxPoolSize=50;Packet Size=8192;ServerType=0;")
    Dim startdate As String = DateTimePicker1.Value.ToString("dd.MM.yyyy")
    Dim enddate As String = Microsoft.VisualBasic.DateAdd(DateInterval.Day, 1, DateTimePicker2.Value).ToString("dd.MM.yyyy")
    Dim adapter As New FbDataAdapter("SELECT * from ORDER WHERE DATEORDER BETWEEN @StartDate AND @EndDate AND ZIPCODE = CASE WHEN  @Param1 IS NULL THEN ZIPCODE ELSE @Param1 END ", conn)
    
    adapter.SelectCommand.Parameters.AddWithValue("@Param1", ComboBox5.Text)
    adapter.SelectCommand.Parameters.AddWithValue("@Param2", ComboBox3.Text)

    Dim table As New DataTable

    adapter.Fill(table)
    DataGridView1.DataSource = table
End Sub
4

1 回答 1

2

通常,您可以编写带有可选参数的查询,如下所示:

Dim query = "SELECT *
             FROM MyTable
             WHERE (@Column1 IS NULL OR Column1 = @Column1)
             AND (@Column2 IS NULL OR Column2 = @Column2)"
Dim command As New SqlCommand(query, connection)

With command.Parameters
    .Add("@Column1", SqlDbType.VarChar, 50).Value = If(ComboBox1.SelectedItem Is Nothing, CObj(DBNull.Value), ComboBox1.Text)
    .Add("@Column2", SqlDbType.VarChar, 50).Value = If(ComboBox2.SelectedItem Is Nothing, CObj(DBNull.Value), ComboBox2.Text)
End With

如果在 a 中未选择任何项目,ComboBox则相应的参数设置为 NULL,并且相应的标准匹配所有记录,有效地忽略该参数。

上面的代码是为 SQL Server 编写的,我不使用 Firebird,所以我不确定哪些细节会发生变化,但原则适用于任何数据库。如果 Firebird 提供程序不支持命名参数(Access 数据库就是这种情况),那么需要进行的一项更改是您需要为每列添加两个参数而不是一个,例如

Dim query = "SELECT *
             FROM MyTable
             WHERE (@Column1A IS NULL OR Column1 = @Column1B)
             AND (@Column2A IS NULL OR Column2 = @Column2B)"
Dim command As New SqlCommand(query, connection)

With command.Parameters
    .Add("@Column1A", SqlDbType.VarChar, 50).Value = If(ComboBox1.SelectedItem Is Nothing, CObj(DBNull.Value), ComboBox1.Text)
    .Add("@Column1B", SqlDbType.VarChar, 50).Value = If(ComboBox1.SelectedItem Is Nothing, CObj(DBNull.Value), ComboBox1.Text)
    .Add("@Column2A", SqlDbType.VarChar, 50).Value = If(ComboBox2.SelectedItem Is Nothing, CObj(DBNull.Value), ComboBox2.Text)
    .Add("@Column2B", SqlDbType.VarChar, 50).Value = If(ComboBox2.SelectedItem Is Nothing, CObj(DBNull.Value), ComboBox2.Text)
End With
于 2021-05-05T05:02:50.707 回答