Connect VB.NET and Access Database - Example Code

Submitted by techrev on Mon, 01/22/2018 - 09:40

Connect to a database (here “Bin” folder, then insert values) – basic cad example

 

Imports System.Data.OleDb

Imports System.IO

 

‘Under Public Class Form1

 

Dim provider As String

    Dim dataFile As String

    Dim dataFilemaster As String

    Dim conline As New OleDbConnection

    'Dim conmaster As New OleDbConnection

    ' Dim connection1 As New OleDbConnection

    Dim connString As String

    ' Dim connStringmaster As String

    Dim path1 As String

    Public dr As OleDbDataReader

 

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        provider = "provider=Microsoft.ACE.OLEDB.12.0;Data Source="

        'dataFile = "C:\Basic-CAD-data.accdb"

        dataFile = "..\\Basic-CAD-data.accdb"        'CHANGE FILE LOCATION

        connString = provider & dataFile

        conline.ConnectionString = connString

 

 

        ' con.ConnectionString = "provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\\Basic-CAD-data.accdb;"      'CHANGE FILE LOCATION or use dataFile (above)

    End Sub

‘under any button click

 

conline.Open()

Dim strline As String

                    Dim YES As String

                    YES = "YES"

                    strline = "insert into Table1 ([linex], [liney], [isline]) values (?, ?, ?)"                         ' CHANGE TABLE NAME

                    Dim cmdline As OleDbCommand = New OleDbCommand(strline, conline)

                    cmdline.Parameters.Add(New OleDbParameter("linex", CType(lineX2(j), Integer)))

                    cmdline.Parameters.Add(New OleDbParameter("liney", CType(lineY2(j), Integer)))

                    cmdline.Parameters.Add(New OleDbParameter("isline", CType(YES, String)))

                    Try

                        cmdline.ExecuteNonQuery()

                        cmdline.Dispose()

                        'TextBox1.Clear()

                    Catch ex As Exception

                        'MsgBox(ex.Message)

                    End Try

conline.Close()