Friday, March 18, 2011

How to Connect to a database using ADO type and retrieving the data.


'How to Connect to a database using ADO and retrieving the data.
'Create a reference to 'Microsoft ActiveX Data Object 2.0 Library'

Private Sub Form_Load()
    'Declare the connection and recordset objects
    Dim cnData As Connection
    Dim recordset1 As Recordset

    'Instantiate the objects
    Set Conn = New Connection
    Set recordset1 = New Recordset

    'Set the connection string
    Conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=<<PATH TO DATABASE>>"
    Conn.Open

    'Code to test the connection
    If Conn.State = adStateOpen Then MsgBox "Connection good."

    'Get data from the database connection
    recordset1.Open "<<SQL STATEMENT>>", Conn

    'For testing purposes, write to debug window
    Debug.Print recordset1!<<DATABASE_COLUMN_FIELD_NAME>>

    'Make sure to close the connection and release Conn
    Conn.Close
    Set Conn = Nothing
End Sub

0 comments:

Post a Comment

 
Powered by Blogger