如何在 vb.net 中构建对 sql 数据库的动态查询

how to build dynamic query to sql database in vb.net

我想使用动态查询来填充组合框。为此,它是在外部 class 创建的,名为 sqlcnn。此 class 定义了与 sql 数据库的连接并且它工作正常。下面是代码:

Imports System.Data.SqlClient

Public Class sqlcnn

Public cnn As New SqlConnection("Data Source=(local)\sqlexpress...)
Public Command As SqlCommand
Public txt() As String
Public i As Integer

Public Sub execute_command(ByVal query As String)

    Try
        cnn.Open()

        Command = New SqlCommand(query, cnn)

        Dim readerr = Command.ExecuteReader

        ReDim txt(readerr.FieldCount - 1)

        While readerr.Read


            For i = 0 To readerr.FieldCount - 1
                txt(i) = readerr.Item(i)

            Next i


        End While

        MsgBox("Connection Open ! ")
        cnn.Close()
    Catch ex As Exception
        MsgBox("Can not open connection ! ")
    End Try


End Sub

结束Class

如果我修改上面的代码,在for循环中多加一行:

 For i = 0 To readerr.FieldCount - 1
                txt(i) = readerr.Item(i)
                ComboBox1.Items.Add(txt(i))

            Next i

我可以立即填充组合框,没有任何问题。

问题是,当我尝试从名为 Form1 的主 class 填充组合框时。 这个 class 定义了一个 combobox1 和一个按钮。下面是代码:

Imports System.Data.SqlClient

Public Class Form1

Private Sql As New sqlcnn
Dim i As Integer

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Sql.execute_command("select Car from shopcars")

    For i = 0 To (Sqlpol.txt.Length - 1)

        ComboBox1.Items.Add(Sqlpol.txt(i))

    Next i


End Sub

结束class

结果是,在组合框中我们只能看到我的数据库的最后一项。完全,我不知道如何正确构建 for 循环。 我很感激你的帮助。

谢谢!

txt是一维数组。 While 的每次迭代都会覆盖 txt 索引 0 到索引 readerr.FieldCount。这就是为什么它总是包含最后一行的数据。 您需要一个支持多行的不同数据结构。有很多选择。我会推荐一个 DataTable,因为您可以将它绑定到您的组合框,而不是在循环中添加项目。