Connecting To An Access Database Using ASP

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 9

Connecting To An Access

Database Using ASP


Difficulty:

Demo: Sample Guestbook

Download: database_tutorials.zip

If you are reading this page then I shall assume that you already know a little bit about ASP and running ASP
applications.

To make this tutorial more interesting and the following database tutorials on, Adding, Deleting, and Updating,
data from a Microsoft Access database, we are going to use these tutorials to make a simple Guestbook
application.

Before we can connect to a database we need a database to connect too.

Creating the Guestbook


Database
To create a database your first need to open Microsoft Access and choose 'Blank Access Database' from the
starting menu. You will be prompted for a name for the database and where you want it saved. Call the database
'guestbook.mdb' and save it in the same directory as the web page connecting to the database is going to be.

You should now see the main Access dialog box, from here select 'Create table in design view'.

You now need to create 3 fields for the database and select their data types.

Field 1 needs to be called 'ID_no' and have the data type of 'AutoNumber'. Also set this field as the primary key.

Field 2 needs to be called 'Name' and have the data type of text.

Field 3 needs to be called 'Comments' and also has the data type of text, but this time you need to change the
default field size of 50 to 100 characters under the 'General' tab in the 'Field Properties' box at the bottom of the
screen.
Once all the field's have been created and the data types and primary key set, save the table as 'tblComments'.

Now the table has been created you need to enter some test data into the table. You can do this by double-
clicking on the new table (tblComments) in the main dialog box. From here you can enter some test data. I would
recommend entering at least 3 pieces of test data.

If you are having trouble creating the database then you can download this tutorial containing the Access
Database with test data already entered.

Connecting to the Guestbook


Database
Now that the database is created and test data entered we can get on with creating the web page to display the
data from the database.

First we need to start web page, open up your favourite text editor and type the following HTML.

<html>
<head>
<title>My First ASP Page</title>
</head>
<body bgcolor="white" text="black">

Next we can begin writing the ASP to connect to the database. First we need to create the variables that we are
going to use in the script.

<%
'Dimension variables
Dim adoCon 'Holds the Database Connection Object
Dim rsGuestbook 'Holds the recordset for the records in the database
Dim strSQL 'Holds the SQL query to query the database

Next we need to create a database connection object on the server using the ADO Database connection object.

'Create an ADO connection object


Set adoCon = Server.CreateObject("ADODB.Connection")

Now we need to open a connection to the database. There are a couple of ways of doing this either by using a
system DSN or a DSN-less connection. First I am going to show you how to make a DSN-less connection as this
is faster and simpler to set up than a DSN connection.

To create a DSN-less connection to an Access database we need tell the connection object we created above to
open the database by telling the connection object to use the 'Microsoft Access Driver' to open the database
'guestbook.mdb'.

You'll notice the ASP method 'Server.MapPath' in font of the name of the database. This is used as we need to
get the physical path to the database. Server.MapPath returns the physical path to the script, e.g. 'c:\website\',
as long as the database is in the same folder as the script it now has the physical path to the database and the
database name.

'Set an active connection to the Connection object using a DSN-less connection


adoCon.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Server.MapPath("guestbook.mdb")

If on the other hand you want to use a slower DSN connection to the database then you will need to replace the
line above with the one below. Also if you don't know how to setup a system DSN you will need to read my
tutorial on, Setting up a System DSN.

'Set an active connection to the Connection object using DSN connection


adoCon.Open "DSN=guestbook"

Next create an ADO recordset object which will hold the records from the database.

'Create an ADO recordset object


Set rsGuestbook = Server.CreateObject("ADODB.Recordset")

To query a database we need to use SQL (Structured Query Language). In the next line we initialise the variable
'strSQL' with an SQL query to read in the fields 'Name' and 'Comments' form the 'tblComments' table.

'Initialise the strSQL variable with an SQL statement to query the database
strSQL = "SELECT tblComments.Name, tblComments.Comments FROM tblComments;"

Now we can open the recordset and run the SQL query on the database returning the results of the query to the
recordset.

'Open the recordset with the SQL query


rsGuestbook.Open strSQL, adoCon

Using a 'Do While' loop we can loop through the recordset returned by the database while the recordset is not at
the end of file (EOF). The 'Response.Write' method is used to output the recordset to the web page. The
'MoveNext' method of the recordset object is used to move to the next record in the recordset before looping
back round to display the next record.

'Loop through the recordset


Do While not rsGuestbook.EOF

'Write the HTML to display the current record in the recordset


Response.Write ("<br>")
Response.Write (rsGuestbook("Name"))
Response.Write ("<br>")
Response.Write (rsGuestbook("Comments"))
Response.Write ("<br>")

'Move to the next record in the recordset


rsGuestbook.MoveNext
Loop

And finally we need to close the recordset, reset the server objects, close the server side scripting tag, and close
the html tags.

'Reset server objects


rsGuestbook.Close
Set rsGuestbook = Nothing
Set adoCon = Nothing
%>

</body>
</html>

Now call the file you have created 'guestbook.asp' and save it in the same directory folder as the database, don't
forget the '.asp' extension.

And that's about it, you have now created a connection to a database and displayed you Guestbook in a web
page, now to find out how add comments to the Guestbook through a web form read the next tuorial on, Adding
Data to an Access Database.

If you find that you are getting errors connecting to the database then please read through the Access Database
Errors FAQ's, practically make sure you have the correct 'ODBC Drivers' installed on your system and if you are
using the, 'NTFS file system', make sure the permissions are correct for the database and the directory the
database in.

Adding Data to An Access


Database Using ASP
Difficulty:

Author: -borg-

Demo: Adding Data to Database An Access Database

Download: database_tutorials.zip

In this tutorial we are going to be adding data to the Guestbook database made in the tutorial Part: 1 Connecting
to an Access Database.

To make the Microsoft Access database tutorials on Connecting, Adding, Deleting, and Updating, more interesting
we are going to use these tutorials to make a simple Guestbook.

In the first database tutorial, Part: 1 Connecting to an Access Database, we learned how to connect to a database
and display the contents of a database table in a web page.

In this tutorial we use an HTML form to take a site visitors name and comments and add these to the database.
We will then use the page 'guestbook.asp' made in the first database tutorial to display the contents of the
database (don't worry if you didn't do the first database tutorial, the 'Guestbook database' and the
'guestbook.asp' page are included in the zip file for this tutorial).

Creating an HTML Page to take


User Input
First we need to quickly create an HTML page with a form on it to take the input from the user.

In this page we will have two text boxes, one called 'name' and the other called, 'comments', we will then use the
post method to send the page to the file, 'add_to_guestbook.asp' that we are going to be creating later in this
tutorial, which will add the user input into the database.
<html>
<head>
<title>Guestbook Form</title>
</head>
<body bgcolor="white" text="black">
<!-- Begin form code -->
<form name="form" method="post" action="add_to_guestbook.asp">
Name: <input type="text" name="name" maxlength="20">
<br>
Comments: <input type="text" name="comments" maxlength="50">
<input type="submit" name="Submit" value="Submit">
</form>
<!-- End form code -->
</body>
</html>

Save the page as 'guestbook_form.htm' in the same folder as the Guestbook database.

Adding Data to the Guestbook


Database
Now we've got the form, to input the data through, out of the way we can make the the page that does all the
work, adding the data to the database.

This page contains no HTML so we can start writing the asp straight away, still don't forget the server side script
tags, <% .... %>.

First we need to dimension the variables used in the script, so open your favourite text editor and enter the
following code.

<%
'Dimension variables
Dim adoCon 'Holds the Database Connection Object
Dim rsAddComments 'Holds the recordset for the new record to be added
Dim strSQL 'Holds the SQL query to query the database

Next we need to create a database connection object on the server using the ADO Database connection object.

'Create an ADO connection object


Set adoCon = Server.CreateObject("ADODB.Connection")

Now we need to open a connection to the database. There are a couple of ways of doing this either by using a
system DSN or a DSN-less connection. First I am going to show you how to make a DSN-less connection as this
is faster and simpler to set up than a DSN connection.

To create a DSN-less connection to an Access database we need tell the connection object we created above to
open the database by telling the connection object to use the 'Microsoft Access Driver' to open the database
'guestbook.mdb'.

You'll notice the ASP method 'Server.MapPath' in font of the name of the database. This is used as we need to
get the physical path to the database. Server.MapPath returns the physical path to the script, e.g. 'c:\website\',
as long as the database is in the same folder as the script it now has the physical path to the database and the
database name.

'Set an active connection to the Connection object using a DSN-less connection


adoCon.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Server.MapPath("guestbook.mdb")

If on the other hand you want to use a slower DSN connection to the database then you will need to replace the
line above with the one below. Also if you don't know how to setup a system DSN you will need to read my
tutorial on, Setting up a System DSN.
'Set an active connection to the Connection object using DSN connection
adoCon.Open "DSN=guestbook"

Next create an ADO recordset object which will hold the records from the database and the new record to be
added to the database.

'Create an ADO recordset object


Set rsAddComments = Server.CreateObject("ADODB.Recordset")

To query a database we need to use SQL (Structured Query Language). In the next line we initialise the variable
'strSQL' with an SQL query to read in the fields 'Name' and 'Comments' form the 'tblComments' table.

'Initialise the strSQL variable with an SQL statement to query the database
strSQL = "SELECT tblComments.Name, tblComments.Comments FROM tblComments;"

Set the cursor type we are using to 'adLockOptomistic' so we can move through the recrord set. The integer
value for this is 2.

'Set the cursor type we are using so we can navigate through the recordset
rsAddComments.CursorType = 2

Because we are going to be saving an updated recordset back to the database we need to set the LockType of
the recordset to 'adoLockOptimistic' so that the recordset is locked, but only when it is updated. The integer
value for this lock type is 3.

'Set the lock type so that the record is locked by ADO when it is updated
rsAddComments.LockType = 3

Now we can open the recordset and run the SQL query on the database returning the results of the query to the
recordset.

'Open the recordset with the SQL query


rsAddComments.Open strSQL, adoCon

Once the recordset is open we can add a new record onto the end of the recordset. In the next line we let the
recordset know we are adding a new record to it.

'Tell the recordset we are adding a new record to it


rsAddComments.AddNew

Now we can add a new record to the recordset. The details taken from the form we created at the start of this
tutorial are entered into there relevant fields in the recordset. To get the data entered by the user from the form
we use the 'Form' method of the ASP 'Request' object to request the data entered into the text boxes, 'name' and
'comments'.

'Add a new record to the recordset


rsAddComments.Fields("Name") = Request.Form("name")
rsAddComments.Fields("Comments") = Request.Form("comments")

The data has been entered into the recordset we can save the recordset to the database using the 'Update'
method of the recordset object.

'Write the updated recordset to the database


rsAddComments.Update

We have finished using the database in this script so we can now close the recordset and reset the server
objects.

'Reset server objects


rsAddComments.Close
Set rsAddComments = Nothing
Set adoCon = Nothing

Now that the database is updated we are going to use the 'Redirect' method of the ASP response object to
redirect to the 'guestbook.asp' page we created in the first database tutorial, Connecting to an Access Database,
so we can display the updated database. Note that if you are going to use the 'Response.Redirect' method you
must remember to redirect before any HTML is written.

'Redirect to the guestbook.asp page


Response.Redirect "guestbook.asp"
%>

Now call the file 'add_to_guestbook.asp' and save it to the same directory as the database and the
'guestbook.asp' page, don't forget the '.asp' extension.

And that's about it, you have now created a simple Guestbook for your web site, to find out how to delete any of
the comments from the Guestbook database read the next tutorial on, Deleting Data from an Access Database.

If you find that you are getting errors connecting to the database then please read through the Access Database
Errors FAQ's, practically make sure you have the correct 'ODBC Drivers' installed on your system and if you are
using the, 'NTFS file system', make sure the permissions are correct for the database and the directory the
database in.

ASP Source Code:


<%
Dim DataConn, cmdDC, rsDC
Dim Item
Dim iFieldCount, iLoopVar
Dim strLTorGT, iCriteria, strSortBy, strOrder

' Retrieve QueryString Variables and convert them to a usable form


strLTorGT = Request.QueryString("LTorGT")
Select Case strLTorGT
Case "LT"
strLTorGT = "<"
Case "GT"
strLTorGT = ">"
Case Else
strLTorGT = "<>"
End Select

iCriteria = Request.QueryString("criteria")
If IsNumeric(iCriteria) Then
iCriteria = CLng(iCriteria)
Else
iCriteria = 0
End If

strSortBy = Request.QueryString("sortby")
Select Case LCase(strSortBy)
Case "id", "last_name", "first_name", "sales"
strSortBy = LCase(strSortBy)
Case Else
strSortBy = "last_name"
End Select
strOrder = Request.QueryString("order")
If strOrder <> " DESC" Then strOrder = ""
' Finally we've got all our info, now to the cool stuff

' Create and establish data connection


Set DataConn = Server.CreateObject("ADODB.Connection")
DataConn.ConnectionTimeout = 15
DataConn.CommandTimeout = 30

'Access connection code


'DataConn.Open "DBQ=" & Server.MapPath("database.mdb") &
";Driver={Microsoft Access Driver
(*.mdb)};DriverId=25;MaxBufferSize=8192;Threads=20;", "username",
"password"

'Our SQL Server code - use above line to use sample on your server
DataConn.Open "Provider=SQLOLEDB;Data Source=10.2.2.133;" _
& "Initial Catalog=samples;User Id=samples;Password=password;" _
& "Connect Timeout=15;Network Library=dbmssocn;"

' Create and link command object to data connection then set attributes
and SQL query
Set cmdDC = Server.CreateObject("ADODB.Command")
cmdDC.ActiveConnection = DataConn
cmdDC.CommandText = "SELECT * FROM sample WHERE (sales " & strLTorGT &
" " & iCriteria & ") ORDER BY " & strSortBy & strOrder & ";"
cmdDC.CommandType = 1

' Create recordset and retrieve values using command object


Set rsDC = Server.CreateObject("ADODB.Recordset")
' Opening record set with a forward-only cursor (the 0) and in read-
only mode (the 1)
rsDC.Open cmdDC, , 0, 1
%>

<p><strong>Results of <%= cmdDC.CommandText %></strong></p>

<table border="1">
<thead>
<tr>
<% For Each Item in rsDC.Fields %>
<th><%= Item.Name %></th>
<% Next %>
</tr>
</thead>
<%
' Loop through recordset and display results
If Not rsDC.EOF Then rsDC.MoveFirst

' Get the number of fields and subtract one so our loops start at 0
iFieldCount = rsDC.Fields.Count - 1

' Continue till we get to the end, and while in each <TR> loop through
fields
Do While Not rsDC.EOF
%> <tr>
<% For iLoopVar = 0 to iFieldCount %>
<td><%= rsDC.Fields(iLoopVar) %></td>
<% Next %>
</tr>
<%
rsDC.MoveNext
Loop
%>
</table>

<%
' Close Data Access Objects and free DB variables
rsDC.Close
Set rsDC = Nothing
' can't do a "cmdDC.Close" !
Set cmdDC = Nothing
DataConn.Close
Set DataConn = Nothing
%>

<br />

<strong>Build your own query:</strong>


<form action="<%= Request.ServerVariables("URL") %>" method="get">
Sales:
<input type="radio" name="LTorGT" value="LT" checked />Less Than
<input type="radio" name="LTorGT" value="GT" />Greater Than
<input type="text" name="criteria" value="4500" size="10" />
<br />
Sort By:
<select name="sortby">
<option value="id">ID</option>
<option value="last_name">Last Name</option>
<option value="first_name">First Name</option>
<option value="sales">Sales</option>
</select>
<select name="order">
<option value="">Ascending
<option value=" DESC">Descending
</select>
<br />
<input type="submit" value="Run Query" />
</form>

You might also like