Write or Insert Records to Access (2007) Database Table - Visual Basic .NET

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

In this tutorial, we will write to Access Database. You will be able to learn how to insert new records in the access table. First create a table with the following fields:

create access table in visual basic .net

Create a form and add 5 textboxes like I have in the following form:


write to access table in visual basic

Add the following code to the top of your code above the (Public Class Form1) line

Imports System.Data.OleDb

Then add the followind declarations below the (Public Class Form1) line

    Dim provider As String
    Dim dataFile As String
    Dim connString As String
    Dim myConnection As OleDbConnection = New OleDbConnection

Then add the followind code that will handle the save button.

Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
        'Change the following to your access database location
        dataFile = "C:\Users\Jimmy\Documents\Test Database.accdb"
        connString = provider & dataFile
        myConnection.ConnectionString = connString

        Dim str As String
        str = "insert into Items ([UPC], [Item], [Cost], [Price], [Quantity]) values (?, ?, ?, ?, ?)"
        Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
        cmd.Parameters.Add(New OleDbParameter("UPC", CType(TextBox1.Text, String)))
        cmd.Parameters.Add(New OleDbParameter("Item", CType(TextBox2.Text, String)))
        cmd.Parameters.Add(New OleDbParameter("Cost", CType(TextBox3.Text, String)))
        cmd.Parameters.Add(New OleDbParameter("Price", CType(TextBox4.Text, String)))
        cmd.Parameters.Add(New OleDbParameter("Quantity", CType(TextBox5.Text, String)))
        Catch ex As Exception
        End Try

    End Sub

You can also use the online code generator to get the above code

Share This

Home | About | Contact | Privacy Policy

Copyright visual-basic-tutorials.com 2018 - All Rights Reserved.