Friday, August 12, 2011 | By: nika perales

VB.net: connect to ms access database

Here's how to connect to an MS Access Database from VB.Net and add a new record. The sample code uses the OleDbConnection object as a means of connecting to the MS Access Database...

Imports System.Data

Public Class UsingMsAccess


Private Sub AddNewRecord()
'Replace path to "accessdatabasepath" with the actual path to the ms access database
	'example C:\testApp\data\mydata.mdb
        Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=accessdatabasepath"
        Dim dbConnection As DbConnection = New OleDbConnection(connectionString )
	
        Dim queryStr As String = "SELECT [Employees].* FROM [Employees]"
        Dim dbCommand As DbCommand = New OleDbCommand
        
        dbConnection.Open()
	dbCommand.CommandText = queryString
        dbCommand.Connection = dbConnection

        Dim dataAdapter As DbDataAdapter = New OleDbDataAdapter
        Dim commandBuilder as DbCommandBuilder= New OleDbCommandBuilder(dataAdapter)
	dataAdapter.SelectCommand = dbCommand
        Dim MydataSet As DataSet = New DataSet
        dataAdapter.Fill(MydataSet,"Employees") 'where employees is the name of the datatable
        
	dim NewRow as datarow = MydataSet.tables("Employees").Newrow
	NewRow("Name") = "sammy" 'Replace ("Name") with your own table field name
	NewRow("Age") = 27
	
	MydataSet.tables("Employees").Rows.Add(NewRow)
	dataAdapter.Update(MydataSet,"Employees")
	MydataSet.tables("Employees").AcceptChanges()

End Sub
 

0 comments:

Post a Comment