Insert Records into Access database with ADO.NET

The following code inserts a record into the Microsoft Access database every time the Page_Load event is raised i.e. every time the page is requested. The Access database is called 'Customers' and has a table called 'tblCustomers'. The table has a primary key autonumber field 'ID', and two textfields 'FirstName' and 'LastName'. The database is located in the folder 'H:\Inetpub\wwwroot\code\Customers.mdb'.

The code simply inserts the firstname 'Michael' and the lastname 'Wall' each time. A label control 'label1' displays the text 'Record inserted.' after the new record has been inserted.

<%@ Page Language="VB" %>

<%@ Import Namespace="System.Data.Oledb" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

Protected Sub Page_Load()

    Dim Connection As New OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0;" & _
    "Data Source=H:\Inetpub\wwwroot\code\Customers.mdb")
    Connection.Open()

    Dim Command As New OleDbCommand("INSERT INTO tblCustomers" & _
    "(FirstName, LastName)VALUES(@FirstName,@LastName)", Connection)
    Command.Parameters.Add(New OleDbParameter("@FirstName", "Michael"))
    Command.Parameters.Add(New OleDbParameter("@LastName", "Wall"))
    Command.ExecuteNonQuery()

    Connection.Close()
    Label1.Text = "Record Inserted."

End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head id=Head1 runat="server">
<title>Insert Customers</title>
</head>

<body>

<form id="form1" runat="server">

<div>
<asp:Label ID=Label1 runat="server" Text="Label"></asp:Label>
</div>

</form>

</body>
</html>

Get the best asp web hosting provider now and save 30%

Advertisements



MembersPro

MembersPro PayPal - ASP Membership software

Plug and play ASP membership script that integrates with PayPal to let you charge recurring membership fees.