Linking a Database in Visual Basic??

Soldato
Joined
18 Oct 2002
Posts
4,020
Location
Wellington, NZ
Hiya, as part of my course we were sent off to do a project and part of it is linking a VB program to a Database (so that it displays the DB and you can add/delete records in VB)

In the earlier tutorials for this it just says 'add a module 1st which was already created for you, and then link the database.

The problem i've got is how the heck are we supposed to know the code for this module so we can add our database?? Alternatively is there an easier way of linking a DB in VB?

TIA.
 
It's really easy, have you tried looking on MSDN?

Try the keyworlds OleDb on the serach there. It's easiest with SQL Server as your database but you can connect to pretty much anything using ODBC.

HT
 
You can connect to Access like this from Code. Not you will need to make a reference to ADO, it will probably be either 2.7 or 2.8 any is fine though.
Code:
Public Function ConnectDB()
    Dim cnString As String
        cnString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                   "Data Source=" & App.Path & "\YourDatabase.mdb"

    Dim sqlString As String
        sqlString = "SELECT * " & _
                    "FROM YourTable"
    
    Dim CN As ADODB.Connection
    Set CN = New ADODB.Connection
        CN.Open cnString

    Dim RS As ADODB.Recordset
    Set RS = New ADODB.Recordset
        RS.CursorLocation = adUseClient
        RS.Open sqlString, CN, adOpenStatic, adLockOptimistic

    Set YourForm.YourFlexGrid.DataSource = RS
    
        CN.Close
    Set RS = Nothing
    Set CN = Nothing
End Function

This will fill a FlexGrid with all the records from the selected table.

You can of course change the SQL Command to do what you like, Update, Delete, Insert etc...

Hope this helps,

sfx
 
Back
Top Bottom