1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Linking a Database in Visual Basic??

Discussion in 'HTML, Graphics & Programming' started by AmDaMan, 22 Jan 2006.

  1. AmDaMan


    Joined: 18 Oct 2002

    Posts: 3,971

    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?

  2. happytechie


    Joined: 18 Oct 2002

    Posts: 5,601

    Location: Surrey

    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.

  3. roboffer


    Joined: 18 Oct 2002

    Posts: 9,599

    Location: Sunderland

  4. sfx


    Joined: 13 Dec 2004

    Posts: 926

    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.
    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
        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,