这是从数据库获取数据到 datagridview 的最有效方式吗?

Is this the most efficient way to get data from database to datagridview?

Im a beginner and hoping to know whats the most memory/processor efficient way to query. Am i placing the using and end using properly?. Is the New OleDbCommand still needed? Please comment your suggestions and tips to improve my code :)

    Dim con As New OleDbConnection
 Dim dbProvider As String = "Provider=Microsoft.ACE.OLEDB.12.0;"
      Dim dbSource As String = ("Data Source=" & Application.StartupPath & "\DBbms.accdb")
       con.ConnectionString = dbProvider & dbSource
       

Using connection As New OleDbConnection(con.ConnectionString)
        Try

            Dim query As String = "Select * from Household"
            'cmd = New OleDbCommand(query, con)
            Dim da As New OleDbDataAdapter(query, con)

            connection.Open()
            Dim dt As New DataTable
            da.Fill(dt)


            DataGridView1.DataSource = dt.DefaultView


        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Using

将用户界面代码与数据库代码分开。如果您想在 Catch 中显示消息框,请在 UI 代码中执行此操作。

您可能希望将连接字符串设为 class 级变量,以便其他数据库代码可以使用它。

该命令也包含在 Using 块中。请注意 Connection 行末尾的逗号。

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim dt As DataTable
    Try
        dt = GetHouseholdData()
    Catch ex As Exception
        MsgBox(ex.Message)
        Exit Sub
    End Try
    DataGridView1.DataSource = dt.DefaultView
End Sub

Private HHConStr As String = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={Application.StartupPath}\DBbms.accdb"

Private Function GetHouseholdData() As DataTable
    Dim dt As New DataTable
    Using con As New OleDbConnection(HHConStr),
            cmd As New OleDbCommand("Select * from Household", con)
        con.Open()
        Using reader = cmd.ExecuteReader
            dt.Load(reader)
        End Using
    End Using
    Return dt
End Function