How to Connect Visual Basic.Net to MS Access Database

1
1934

Today I will show you how to connect Visual Basic.Net to MS Access Database. This tutorial will be a big help for those individual who finds difficulties in connecting the MS Access database to Visual Basic. Before we begin let’s create first a MS Access database and name it as “firstDB” then create a table named “tblstudent” and this looks like as shown below.

tblstudents

Next, we will create a Visual Basic application, then Add a button this will look like as shown below.

frmconnect

 

Then we will now add functionality to our application. To do this, double click our form  and the following code below Public class:

  1. Dim con As New OleDb.OleDbConnection

The code above simply Initializes a new instance of the OleDbConnection class.

Next, Double click the “Test Connection” button and add the following code:

  1. conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\firstDB.accdb"

The added line of code, we simply use the two technologies called: Provider and Data Source. Without this, we cannot connect to our database because this is where we specify what type of database provider and the Data source of our database used for this connection. And we use also the “Application.StartupPath” where it is the path for executable file that has started the application, and this location also where we are going to put our database file.

conn.ConnectionString = “Provider=Microsoft.ACE.OLEDB.12.0;Data Source=” & Application.StartupPath & “\firstDB.accdb”

 

Under the code above, add another sets of code:

  1. Try
  2. 'opens the connection
  3. conn.Open()
  4.  
  5. If conn.State = ConnectionState.Open Then
  6.  
  7. MsgBox("MS Database Connected!")
  8.  
  9. End If
  10. Catch ex As Exception
  11. MsgBox(ex.Message)
  12. End Try
  13. 'close the connection
  14. conn.Close()

.

The new added sets of code will simply check if the connection between Visual Basic.Net and MS Access database has been established successfully.

Download:

You can download the source code here.connectingvbtomsaccess

Reminder!

Make sure that the database file is located inside the debug folder.

 

 

Reader might read also:

 

Facebook Comments
(Visited 2,888 times, 3 visits today)

1 COMMENT

  1. Hello sir When I execute Code:Microsoft.ACE.OLEDB.12.0 I get:Messsage As On your local browser not resister.how can i solve it.please send guide line in my gmail :princebikram80@gmail.com.thank you

LEAVE A REPLY

Please enter your comment!
Please enter your name here