Wednesday, April 13, 2011

This is sample codes in vb.net connecting to MS Access


1. First we create new new project then name it test



2. Add -> New Item -> Module -> Click ADD


3. In the module1 Add this code below
'import this before Module Module1
Imports System.Data.OleDb


'Add this codes below after Module Module1
'Connection String
Public con As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "/db1.mdb;"
Public cnSQL As New OleDb.OleDbConnection

'function to open the connection
Public Sub connection_open()
       Try
            cnSQL = New OleDbConnection(con)
            cnSQL.Open()

            MsgBox("Seccesfully connected")
        Catch Exp As OleDbException
            MsgBox(Exp.Message, MsgBoxStyle.Critical, "SQL Error")

        Catch Exp As Exception
            MsgBox(Exp.Message, MsgBoxStyle.Critical, "General Error")
        End Try
    End Sub


'function to close the connection
Public Sub connection_close()
        cnSQL.Close()
        cnSQL.Dispose()
    End Sub


4.Save the project ->File - > Save all

location: D:\test then click save


5. Create new database
 
-first open MS access 2003 -> click file -> new -> click blank database in the right side bar.



 -File path->D:\test\Test\bin\Debug 
-name it db1.mdb then click create button then after creating close the database

 5. Add button to the Form1

double click the button then add the code below

 connection_open()


6. Run the Project

-Click the button. if it will pop up successfully connected means that you are now connected to the databes.
 

 

No comments:

Post a Comment