通过函数连接到MS Access数据库

时间:2010-01-27 18:35:37

标签: database vb.net ms-access vba module

这是我的功能:

Public Function DBConnection(ByVal path As String)
    ' This function makes the database connection and returns the object
    ' to reference it.
    cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + path + ";")
    cn.Open()
    Return cn
End Function

正如您所看到的,我想初始化数据库连接并将其返回,以便我可以在表单中使用它。这个函数在一个模块中,我的变量如下:

Public cn As OleDbConnection
Public cmd As OleDbCommand
Public dr As OleDbDataReader

但是我不确定如何在我的表单中使用它,我只是调用函数DBConnection然后继续我的SQL语句?或者我还需要做别的事吗?非常感谢帮助,欢呼。

另外,我需要一些意见。我的应用程序依赖于MS Access数据库。是否最好在Form_Load上初始化连接,然后在用户关闭程序时关闭连接,或者在运行查询时打开和关闭连接?我打算在多个表单上使用一些数据库查询,因此我将其放入模块中,但我不是100%关于如何继续这样做。

感谢。

2 个答案:

答案 0 :(得分:1)

来自:How to bind Microsoft Access forms to ADO recordsets

Private Sub Form_Open(Cancel As Integer)
   Dim cn As ADODB.Connection
   Dim rs As ADODB.Recordset

   'Use the ADO connection that Access uses
   Set cn = CurrentProject.AccessConnection

   'Create an instance of the ADO Recordset class, and
   'set its properties
   Set rs = New ADODB.Recordset
   With rs
      Set .ActiveConnection = cn
      .Source = "SELECT * FROM Customers"
      .LockType = adLockOptimistic
      .CursorType = adOpenKeyset
      .Open 
   End With

   'Set the form's Recordset property to the ADO recordset
   Set Me.Recordset = rs

   Set rs = Nothing
   Set cn = Nothing
End Sub

答案 1 :(得分:0)

一些事情。该函数每次调用时都会打开一个连接。您最好确保关闭数据库,否则会开始耗尽内存。

您可能会查看其他一些选项(例如使用NHibernate或其他ORM。)

但是,如果您使用此模型,则可以使用返回的cn来访问您的数据库。