How to Add/Update/Delete Record using MS Access Database

Submitted by: 
Visitors have accessed this post 365508 times.

The primary purpose of this code is to teach beginner programmer to familiarize the concept of database programming.

This is particularly for beginner but may also applicable for intermediate programmer.


Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Comments

hi.. i downloaded your project.. as i study it, i created my own project and copied your code but change the variables and the database.. as i debugged the codes an error came out.. i checked the codes from my project to yours and found no errors..

this is what it said..

Unable to cast object of type 'System.Data.OleDb.OleDbException' to type 'System.Data.OleDb.OleDbDataReader'.

and it's pointing from the module form "FillListView(lvVehicles, GetData(sSql))" line..

thank you very much..

i downloaded your code, studied and copied it but i changed the variables.. but when i run my program it always shows an error..

It says. Unable to cast object of type 'System.Data.OleDb.OleDbException' to type 'System.Data.OleDb.OleDbDataReader'...

What do you think is the problem? The error came from the module form, in the FillListView(lvVehicles, GetData(sSql)) line..

thanks you very much..

it's an error from ur compilation

plzzzz hellp me
i tink i need code if i do plzzzz help me

thank you

I'm using VB.NET 2008 my update code is like that how can tell me the error

Try
If MsgBox("Are You Sure You Wish To Delete " & txtuserid.Text & "?", vbYesNo + vbQuestion, "Delete Record?") = vbYes Then
myconn.Open()
Dim str As String = "delete from useraccount where Userid='" & txtuserid.Text & "'"
Dim cmd As New SqlCommand(str, myconn)
cmd.ExecuteNonQuery()
'Display Success Message
MsgBox("The Record Has Been Deleted Successfully!", vbInformation, "Successful Delete Procedure!")
c.clearallfields(grp.Controls) 'Calling a Private Function To Clear All Fields
Else
'Display 'Delete Procedure Cancelled' Message
MsgBox("The Delete Procedure Was Cancelled!", vbExclamation, "Delete Procedure Cancelled!")
c.clearallfields(grp.Controls) 'Calling a Private Function To Clear All Fields
End If

Me.Close()
MDIParent1.Button3.PerformClick()
myconn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try

//hello i ned the codes for adding and searching editing and updating plz// thanks!!!

arrggghhhh* ang sakit sa ulo magprogram.. ang hirap di ko magawa, saan ba ko magsisimula. patulong naman anu bang magandang gamitin na software para sa payroll system? beginner palang ako sa paggawa ng program, any suggestions? tnx a lot :D

hi............
i need to do library management system using c++ with the backend ms access... can any one tell me how to connect ms access with the c++ coding for library management system

hi...i am new in programming....recently i have download your coding and try to edit or modify it to the program i want....lastly i successful modify it but it can shown the data insert in the list view but the data in successfully insert to ms access d. Can you please help me troubleshoot it?? thanks a lot:)

[email protected]....

i need codes for log in system in c#.net based from ms access database. the user can log in based from the registered/saved username and password in ms access database. i urgently need it. please help. Thanks. T_T...

Hi Master in VB.Net and SQL Server..

Please help me i cannot add new data in sql server as my backend only update are working...

below is my code:

Imports System.Data.SqlClient
Public Class frmUsers
Private cs As New SqlConnection("Data Source = PC_ROB\SQLEXPRESS;Initial Catalog=GTIGOLDEN;Integrated Security=True")
Private da As New SqlDataAdapter("SELECT * FROM tblUsers", cs)
Private ds As New DataSet
Private cmb As New SqlCommandBuilder(da)
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.Top = 200
Me.Left = 200
Me.WindowState = 0
cs.Open()
da.Fill(ds, "tblClients")
dg.DataSource = ds.Tables("tblClients")
cs.Close()
End Sub
Private Sub btnClose_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
Me.Close()
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Dim x As Integer
da.UpdateCommand = cmb.GetUpdateCommand
x = da.Update(ds.Tables("tblUsers"))
MsgBox(x & " Record(s) Updated")
End Sub
Private Sub btnadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnadd.Click
Dim sqlcom As New SqlCommand
sqlcom.Connection = cs

If u_txtempid.Text <> "" And u_txtuname.Text <> "" And u_txtempname.Text <> "" And u_txtupos.Text <> "" And u_cmbacc <> "" And u_txtpass.Text <> "" Then
Call Confields()
dg.Update()
MsgBox("New User has been added., MsgBoxStyle.Information")
End If
Try
Catch ex As Exception
End Try
da.Fill(ds, "tblClients")
dg.DataSource = ds.Tables("tblClients")
End Sub
Private Sub Confields()
dg.DataSource!EmployeeID = u_txtempid.Text
dg.DataSource!UserName = u_txtuname.Text
dg.DataSource!EmployeeName = u_txtempname.Text
dg.DataSource!Position = u_txtupos.Text
dg.DataSource!AccessLevel = u_cmbacc.Text
dg.DataSource!Password = u_txtpass.Text
End Sub
Private Sub Retfields()
u_txtempid.Text = dg.DataSource!EmployeeID
u_txtuname.Text = dg.DataSource!UserName
u_txtempname.Text = dg.DataSource!EmployeeName
u_txtupos.Text = dg.DataSource!Position
u_cmbacc.Text = dg.DataSource!AccessLevel
u_txtpass.Text = dg.DataSource!Password
End Sub
End Class

Hello,

your example helped me a lot.
However, I'm facing a problem:
I did a query according:

  1. Dim sqlQRY As String = "SELECT * FROM JSM_LEDEN WHERE Kaartnummer = " & IntCardNr
  2.  
  3. Dim JSM_DataAdapter As OleDbDataAdapter = New OleDbDataAdapter(sqlQRY, JSM_Conn)
  4.  
  5. Dim JSM_DataSet As DataSet = New DataSet
  6.  
  7. JSM_DataAdapter.Fill(JSM_DataSet, "JSM_Leden")
  8.  
  9. Dim JSM_DataTable As DataTable = JSM_DataSet.Tables("JSM_Leden")
  10.  
  11. Dim row As DataRow
  12. Dim NumLessons As Integer = 0
  13. Dim LastLogDate As Date

.. as the IntCardNr variable is a unique number, the query results in a single row from my database following code displays it:

  1. For Each row In JSM_DataTable.Rows
  2. Txt_Name.Text = row("Naam")
  3. Txt_Forename.Text = row("Voornaam")
  4. Txt_Address.Text = row("Straat")
  5. Txt_City.Text = row("Gemeente")
  6. Txt_Zip.Text = row("Postcode")
  7.  
  8. If IsDBNull(row("Tel")) Then
  9. Txt_Phone.Text = ""
  10. Else
  11. Txt_Phone.Text = row("Tel")
  12. End If
  13.  
  14. If IsDBNull(row("GSM")) Then
  15. Txt_GSM.Text = ""
  16. Else
  17. Txt_GSM.Text = row("GSM")
  18. End If

Now I want to update a couple of fields (LastLog and NumLessons)

  1. If DateDiff(DateInterval.DayOfYear, CurrentDate, LastLogDate) Then
  2. NumLessons = Val(row("Aantal_Lessen")) + 1
  3. 'Update the database
  4. End If

what would be the best approach to achieve this?

Hi,
I need code for add,edit,delete,update records in Access Database using C#.
Plz help me as early as possible. plz provide code me on my mail id: [email protected]

Thank You.

Thanks, you helped me

hai
plz provide me the code for reading the values from textbox in the vb form and get saved to ms access data base
plz send me the code
to [email protected]

matindi tlga ang mga programmer,,,astig...paturo nga..tsk..
gradauting n lmang aq,,haizt

wahahaha. .Dota na lng tayo.. yan kc.

maganda yung parehong kang magaling.. magaling ka mag dota then magaling ka rin mag programming.. dobol kill yun! eh ang dota gawa yan sa VB platform

i'm using ms access 2007 and i need the right code for save using vb.net
my email is
[email protected]

tutorial for vb.net 2008
first import the following in the reference:
3 files of adodb reference files.

Start coding:
Dim dc As New ADODB.Connection
Dim rs As New ADODB.Recordset
dc.Open("Provider = microsoft.jet.oledb.4.0; data source = filename.mdb")
rs.Open("tablefilename", dc, ADODB.CursorTypeEnum.adOpenKeyset, ADODB.LockTypeEnum.adLockOptimistic)
rs.MoveFirst()
rs.AddNew()

rs.Fields("txtsample").Value = txtsample.Text

rs.Update()
rs.Close()
dc.Close()

strDeleted = ExecNonQuery("DELETE Customers.CustomerID FROM Customers WHERE CustomerID= '" & CustomerID & "'")

please..

the 2 "Customers" is the name of the table in MS ACCESS ryt?

how about the three "CustomerID"?

u should mention delete tablename from table where condition thats all

and at last one more single code is not necessary

ok;....

Where CustomerID = table field...
'" & CustomerID & "' = variable... holds the customerId for checking...

I hv made connection with access database successfully. I can Add rows also successfully but unable to update the table.
I can show data in datagridview and want to add new, update, delete the selected rows.
I can add and delete successfully but unable to update the selected rows within database.
I can use the flag property in VB.net. i can add rows with its value property false and want to update the selected row on its value true.
Please help me asap. on the e-mail id
[email protected]

Thanks & regards
Shilpi garg

How to use flag for update a row in sql database by using vb.

dear sir, am added to the records in access ... but i want to change and show records one by one please reply me ...

thanking you always

you can use adodc for that
to show the data one after the other

plz help me
how to add data in database from my windows application
suggest me code with output
thax

It was really useful, thank you for teach us how to do this. :D

Hi,
I want to make two function on single button(Say Update and diplaying textBox). On first click it should shows textbox, which is panel after click on panel's button(say OK) the first button(Update) run second function(Say it get Updated).
Plz help me. :)

sir,
I can't find the step by step process in your zip file. please sir, i need the documentation on how to do it from start to finish. Im new in this kind of programming but i really want to learn. im using visual basic in visual studio express 2010. hoping for your kindness. Thank you so much!

im a beginner in vb.net 2008,i want someone who could help me to develop a simple inventory system using ms access07..i realy appreciate if someone could help me on this...i need it asap,thank you,my e-mail add is [email protected]

this is a single program of all there stuff......................

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace CompleteADO
{
public partial class Form1 : Form
{
SqlDataAdapter da;
DataSet ds;
SqlCommand com;
SqlConnection con;
DataTable dt;
int curr = 0;
int totr = 0;
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
string constring = @"Data Source=DEEPAK-7FD6C5E5\MANISH;Initial Catalog=manishv;Integrated Security=true";
con = new SqlConnection(constring);
con.Open();
com = new SqlCommand("Select * from customer", con);
da = new SqlDataAdapter(com);
ds = new DataSet();
da.Fill(ds, "cust");
dt = ds.Tables["cust"];
curr = 0;
totr = dt.Rows.Count;
fillcontrol();
initlizecomm();
togglecontrol(true);

}

public void fillcontrol()
{
textBox1.Text = dt.Rows[curr]["cid"].ToString();
textBox2.Text = dt.Rows[curr]["nm"].ToString();
textBox3.Text = dt.Rows[curr]["loc"].ToString();
}

private void button2_Click(object sender, EventArgs e)
{
curr++;
if (curr >= totr)
curr = 0;
fillcontrol();
}

private void button3_Click(object sender, EventArgs e)
{
curr--;
if (curr < 0)
curr = totr - 1;
fillcontrol();
}
public void initlizecomm()
{
da.InsertCommand = con.CreateCommand();
da.InsertCommand .CommandText ="insert into customer"+"(cid,nm,loc)"+"values(@cid,@nm,@loc)";
addparams(da.InsertCommand, "cid", "nm", "loc");

da.UpdateCommand = con.CreateCommand();
da.UpdateCommand.CommandText = "update customer set " + "[email protected],[email protected],[email protected] " + "where [email protected]";
addparams(da.UpdateCommand, "cid", "nm", "loc");

da.DeleteCommand = con.CreateCommand();
da.DeleteCommand.CommandText = "delete customer where [email protected]";
addparams(da.DeleteCommand, "cid");
}

public void addparams(SqlCommand com, params string[] col)
{
foreach (string co in col)
{
com.Parameters.Add("@" + co, SqlDbType.Char, 0, co);
}
}
public void togglecontrol(bool val)
{
textBox1.ReadOnly = val;
textBox2.ReadOnly = val;
textBox3.ReadOnly = val;

button1.Enabled = val;
button2.Enabled = val;
button3.Enabled = val;
button4.Enabled = val;
button5.Enabled = val;
button6.Enabled = val;
button7.Enabled = !val;
button8.Enabled = !val;
}

private void button4_Click(object sender, EventArgs e)
{
togglecontrol(false);
}

private void button7_Click(object sender, EventArgs e)
{
DataRow dr = dt.Rows[curr];
dr.BeginEdit();
dr["cid"] = textBox1.Text;
dr["nm"] = textBox2.Text;
dr["loc"] = textBox3.Text;
dr.EndEdit();
da.Update(ds, "cust");
ds.AcceptChanges();
togglecontrol(true);

}

private void button5_Click(object sender, EventArgs e)
{
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
totr = dt.Rows.Count;
curr = totr - 1;
dr["cid"] = totr;
textBox1.Text = totr.ToString() ;
textBox2.Text = "";
textBox3.Text = "";
togglecontrol(false);
}

private void button6_Click(object sender, EventArgs e)
{
DataRow dr = dt.Rows[curr];
dr.Delete();
da.Update(ds, "cust");
ds.AcceptChanges();
totr--;
curr = totr - 1;
fillcontrol();

}
}
}

hello any body that can help me pls

I successfully insert the record from my from to the
ms access database using vb6 with the datagrid

the problem is unable to update the autoNumber

and unable to delete and update the record
as needed.

the code that I use for deleting the record is

Dim iResponce As Integer

iResponce = MsgBox("Do you want to Delete this record?", vbOKCancel + vbQuestion, "Delete")
If iResponce = vbOK Then
rs.Delete
txtOffice_code.Text = ""
CboOffice_name.Text = ""
Else

rs.CancelUpdate
txtOffice_code.Enabled = False
CboOffice_name.Enabled = False

i need delete record from ms access in front end.. pls tel this codngs... [email protected],plz..plz..

I NEED how u add delete records in database
from frontend,in vb.net
pls hepl me for this

my email :[email protected]

i need coding of insert ,update, and delete...... in c sharp plzzzzzzzzzzz help

look for my work.. i have a simple add,edit in c#...
"simple database manipulation in c#"
point to search engine!!!!!!!!!!!

Hi..pls help me in making program that can save, delete, edit and search record..

Hello. I have wasted a lot of time reading and searching the internet for answers to my apparently simple problem. I remembered your site and, tonight, while searching for answers, I stumble on your site by accident -- thank's to Bing.

Anyway, all the examples I run into don't deal with tables that have Primary Keys. I have a small VisualBasic 2010 application that writes to an MS-Access database (*.mdb). Inserting records works, and I had to search hard how to retrieve the Primary Key after insert completed to be able to have it to use as a Foreign Key in my related table. So, my database is very easy, it has only two tables with a one to many relationship.

When I want to update the records, I use the DataAdapter to fill a DataSet. Then I can display the records easily. But the DataAdapter Update method does not work for me, after I make change the fields and want to persist to the DataSource (my MS-Access database).

I suspect VisualBasic will not update the database unless it is instructed specifically on how to deal with the Primary Key issue? At one point, I suspected I have to first update the child table (even though I make no changes to it) in order for the Update on the Parent table to work. But that does not make sense.

I do use CommandBuilder.

[email protected]

every table must have a PKey.. and use dat PrimaryKey in updating ur records..

Each table must have primary key. You do not need to know the primary key of the primary table since updating is done by using a relationship which you set under the dataset designer.

any equivalent itemdata in .net sir? exept the use of class and structures...
any method?

What do you mean by itemdata?

itemdata for combobox and listbox in .NET. obsolete poh kasi itemdata sa .NET..

In .NET version you need to fill the ComboBox using dataset. You can also fill it programmatically using the Add properties.

using the open.record.set command in excel VB I want to find the access record to update and then pass the data to the appropriate fields. Here is the code that doesn't work. It appears not to have bugs - but then there is nothing happening - no updates. I should mention that the "AddNew" part works just not the "edit" part that is down further.

Sub Export_tear_data()
'
' Upload Macro
' Macro recorded 11/18/2009 by LAB1
'

Sheets("Summary").Select
Range("A5").Select
Sheets("Summary").Select
ActiveWorkbook.save
'Application.Quit

Dim db As Database, rs As Recordset, r As Long, sa As Recordset

Set db = OpenDatabase("X:\PAPLab\PAPLabTables.mdb")
' open the database
' get all records in a table

'Start Data Transfer
Set sa = db.OpenRecordset("ResultTens", dbOpenTable)
r = 7 ' the start row in the worksheet
Do While Len(Range("A" & r).Value) > 0
' repeat until first empty cell in column A

If Range("Q" & r).Value = "- No -" And Len(Range("c" & r).Value) > 0 Then ' Checks if record exists
'With sa
sa.AddNew
If IsNumeric(Range("B" & r).Value) Then
sa.Fields("ResultTensSampleNo") = Range("B" & r).Value
End If
If IsNumeric(Range("C" & r).Value) Then
sa.Fields("ResultTensElmMDR1") = Range("C" & r).Value
End If
If IsNumeric(Range("D" & r).Value) Then
sa.Fields("ResultTensElmMDR2") = Range("D" & r).Value
End If
If IsNumeric(Range("E" & r).Value) Then
sa.Fields("ResultTensElmMDR3") = Range("E" & r).Value
End If
If IsNumeric(Range("F" & r).Value) Then
sa.Fields("ResultTensElmMDR4") = Range("F" & r).Value
End If
If IsNumeric(Range("G" & r).Value) Then
sa.Fields("ResultTensElmMDR5") = Range("G" & r).Value
End If
If IsNumeric(Range("J" & r).Value) Then
sa.Fields("ResultTensElmTDR1") = Range("J" & r).Value
End If
If IsNumeric(Range("K" & r).Value) Then
sa.Fields("ResultTensElmTDR2") = Range("K" & r).Value
End If
If IsNumeric(Range("L" & r).Value) Then
sa.Fields("ResultTensElmTDR3") = Range("L" & r).Value
End If
If IsNumeric(Range("M" & r).Value) Then
sa.Fields("ResultTensElmTDR4") = Range("M" & r).Value
End If
If IsNumeric(Range("N" & r).Value) Then
sa.Fields("ResultTensElmTDR5") = Range("N" & r).Value
End If

'Upload Arm Weight

If IsNumeric(Range("R" & r).Value) Then
sa.Fields("ResultTensElmMDArm") = Range("R" & r).Value
End If
If IsNumeric(Range("S" & r).Value) Then
sa.Fields("ResultTensElmTDArm") = Range("S" & r).Value
End If

sa.Update
End If

'If record for sample already exists
If Range("Q" & r).Value = "- Yes -" Then

sa.Edit
If IsNumeric(Range("B" & r).Value) Then
sa.Fields("ResultTensSampleNo") = Range("B" & r).Value
End If
If IsNumeric(Range("C" & r).Value) Then
sa.Fields("ResultTensElmMDR1") = Range("C" & r).Value
End If
If IsNumeric(Range("D" & r).Value) Then
sa.Fields("ResultTensElmMDR2") = Range("D" & r).Value
End If
If IsNumeric(Range("E" & r).Value) Then
sa.Fields("ResultTensElmMDR3") = Range("E" & r).Value
End If
If IsNumeric(Range("F" & r).Value) Then
sa.Fields("ResultTensElmMDR4") = Range("F" & r).Value
End If
If IsNumeric(Range("G" & r).Value) Then
sa.Fields("ResultTensElmMDR5") = Range("G" & r).Value
End If
If IsNumeric(Range("J" & r).Value) Then
sa.Fields("ResultTensElmTDR1") = Range("J" & r).Value
End If
If IsNumeric(Range("K" & r).Value) Then
sa.Fields("ResultTensElmTDR2") = Range("K" & r).Value
End If
If IsNumeric(Range("L" & r).Value) Then
sa.Fields("ResultTensElmTDR3") = Range("L" & r).Value
End If
If IsNumeric(Range("M" & r).Value) Then
sa.Fields("ResultTensElmTDR4") = Range("M" & r).Value
End If
If IsNumeric(Range("N" & r).Value) Then
sa.Fields("ResultTensElmTDR5") = Range("N" & r).Value
End If

sa.Update

End If

'MsgBox ("Sample " & Range("A" & r).Value & " already exists in the tensile data table. ")
'DoEvents

sa.MoveLast
r = r + 1 ' next row
Loop
sa.Close
Set sa = Nothing

Gud day sir

Please I want to know how I can edit and save records into the database. Please i created a form whereby the user will enter a password and will click on a button and the next form will display, but i have tried "Close() code" but it didn't work, please what should I do?

Thanks
Regards,
Chioma

[email protected]

reply

good day!

can you help me about my project. How to connect ms access 2003 to vb

thanx

Pages

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.