Inserting Records into a Database Using ASP

Download the code

The code below simply inserts data into the table called 'tblFriends' in an Access database called 'Friends.mdb'. The table has 3 columns, firstly an 'ID' field that is an autonumber, secondly a field called 'FirstName' which is a textfield and lastly another textfield called 'SurName'.

Our file is called 'insert.asp'.

<%@ Language="VBScript" %>
<% Option Explicit %>
<html>
<head>
<title>Insert into database</title>
</head>
<body>
<%
'declare your variables
dim connection
dim sSQL, sConnString

'declare SQL statement that will query the database
sSQL="INSERT INTO tblFriends (FirstName, SurName) VALUES ('Michael', 'Wall')"

'define the connection string, specify database
'driver and the location of database
sConnString="PROVIDER=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & Server.MapPath("Friends.mdb")


'create an ADO connection object
Set connection = Server.CreateObject("ADODB.Connection")


'Open the connection to the database
connection.Open(sConnString)

'execute the SQL
connection.execute(sSQL)

response.write "The data was inserted successfully."

'close the object and free up resources
Connection.Close
Set Connection = Nothing
%>
</body>
</html>

Remember that if you are using this script keep the page and the database in the same folder otherwise you will have to change the path to the database.
Note that the value of ID in your database table will automatically increase each time you run this script hence the name 'autonumber'. The value of ID will also be unique.
Also note that we haven't used the the recordset object as we are not returning a recordset, we are simply inserting data not retrieving data.


Previous: How to set up a DSN connection

Get the best asp hosting provider from web-hosting-top.com and save up to 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.

Global ASP.NET Hosting Leader - Click Here