Active using asp (Active Server Pages)

advertisement
HHL
Crudding with ASP
i
'Crudding' with ACTIVE SERVER PAGES (ASP)
by
Hugh Lafferty with Oracle bits by Peter Lake
HHL
Crudding with ASP
i
HHL
Crudding with ASP
ii
Table of Contents
1.
Introduction .................................................................................................................................... 1
1.1. Assumptions about the reader ................................................................................................... 2
1.2. Recordset .................................................................................................................................. 2
1.3. Setting up a Connection ............................................................................................................ 2
1.4. Data Source Names (DSNs) and opening connections ............................................................. 2
1.5. Executing SQL ......................................................................................................................... 3
1.6. The first few lines of an ASP script .......................................................................................... 3
1.7. In a nutshell .............................................................................................................................. 4
2. Hello world ...................................................................................................................................... 5
3. Passing information from a Form ................................................................................................. 7
4. Browsing a Table ............................................................................................................................ 9
5. Using Other data sources ............................................................................................................. 11
6. Creating a record ......................................................................................................................... 15
Using AddNew ............................................................................................................................... 15
7. Updating a Record ........................................................................................................................ 19
8. Deleting a record........................................................................................................................... 25
9. Summary ....................................................................................................................................... 28
10.
References ................................................................................................................................. 30
10.1.
Books .................................................................................................................................. 30
10.2.
Web-sites ............................................................................................................................ 30
11.
Self-Test ..................................................................................................................................... 31
12. Suggested Solution to Activity 3b .................................................................................................. 32
Activity 3b ...................................................................................................................................... 32
13.
Tutorial ...................................................................................................................................... 35
HHL
Crudding with ASP
ii
HHL
Crudding with ASP
1
1. Introduction
Active Server Pages (ASP), not to be confused with Application Service Provider (ASP), is a Microsoft
technology, which is free that allows databases to be 'glued' to the Web. The contenders for this area
include



PHP
ColdFusion
Perl
It is assumed that the reader is familiar with the concepts of Web Servers and extensions to them that
allow PHP/ASP/ColdFusion files to produce HTML 'on the fly'. For those readers not familiar with
these concepts, you are recommended to look at the accompanying "Web Servers" presentation.
The only concept that is needed is that these files contain, non-HTML statements, that the extensions
must translate into their HTML equivalents and pass the resulting HTML back to the Web server,
which then passes the HTML on to the client.
We will introduce a few objects, informally, such as


Response
Request
which allows us to write messages back to the client
which allows information to be passed from a calling form to a
called form
If you want to find out more about these objects, and others, in more detail, then look at the
accompanying "ASP Forms" notes.
In what follows we use Dreamweaver as both a text editor and an FTP client. We use the word Put to
mean "use FTP to send to the server". If you do not have Dreamweaver you could just as easily use a)
TextPad (switch line numbering on), and b) WSFTP. If you do not know how to use an FTP client,
then look at the accompanying "How to FTP" notes.
We make the assumption that you are familiar with programming concepts and that you understand
VBScript. If you do not understand VBScript we recommend that you look at the accompanying
"VBScript 3GL " notes.
We start off with a little revision in Activities 1 and 2, where we get you to run a simple Hello World
program and remind you that the contents of most widgets on Forms (with a POST METHOD) are
made available via the Request object's Form method via Request.Form("widgetname").
'Crudding' is a shorthand for "Creating Updating and Deleting" and we include Browsing into
crudding. So, we then move on to show how to Browse a file, Create records in a file, Update records
in a file and Delete records from a file.
HHL
Crudding with ASP
1
HHL
1.1.
Crudding with ASP
2
Assumptions about the reader
We have made a number of assumptions about the reader of these notes, and these are



1.2.
You are already a competent programmer (so we will not bother explaining what a variable is)
You know what a Web server is. If not please refer to the accompanying "Web Server" notes
You know how to FTP. If not please refer to the accompanying "How to FTP" notes
Recordset
There is one important new concept in these notes and that is the idea of a Recordset, which is a copy,
usually in client RAM of a table or query. It is best viewed as a rectangular structure with rows
corresponding to records and columns corresponding to fields, exemplified below
Rs
Customer
CustomerNo
Rs(0).name will yield CustomerNo no matter which record is being pointed to
CustomerTitle
Record 1
Record 2
Record 3
CustFirstName
CustSurname
Rs(2) will yield the contents of CustFirstName of the record being pointed at
We declare a Recordset (Rs, say) which has a pointer pointing to the first record, initially. We need
methods to move the pointer through the Recordset such as MoveNext, MovePrevious,
MoveFirst, MoveLast and we need the Update method to write the Recordset back to the database.
We get at individual fields using something like Rs("CustomerTitle ")
We create a recordset with the following statement
Set Rs=Server.CreateObject("ADODB.RecordSet")
1.3.
It does not have to be Rs it
can be any valid name
Setting up a Connection
In order to create a recordset we must first connect to a database and we do that with this statement
Set MyConn=Server.CreateObject("ADODB.Connection")
1.4.
It does not have to be
MyConn it can be any valid
name
Data Source Names (DSNs) and opening connections
A Data Source Name (DSN) is a pointer to a database. This pointer must have been set up by a system
administrator and can point to a database anywhere in the world. We use the following statement to
open up a connection using a previously created DSN
MyConn.Open("DSN")
HHL
where DSN is set up by an administrator
Crudding with ASP
2
HHL
Crudding with ASP
3
At Sheffield Hallam University there are a number of servers and students are often provided space for
their asp pages on a server called Otho and space for Oracle databases on a server called Ivy, and so we
have this set up
ivy
otho
asp
pages
Oracle
DSNs
s
1.5.
Executing SQL
Having established a connection to a database and declared a Recordset we are now in a position to
execute some SQL to populate the Recordset and we use a statement like this
Rs.Open "SELECT * From Customer", MyConn, 1, 2
which has the syntax
Recordset.Open QueryString, Connection Info, Cursor Type, Lock Type
In the example above, and throughout these notes, we have used 1 and 2 for the latter parameters.
There are some constants, such as adOpenForwardOnly, adLockOptimistic, but locking and cursor
types are outside the scope of this document.
1.6.
The first few lines of an ASP script
The first few lines of an ASP script will be something like these
Option Explicit
You can omit the 1st 2 lines, but it is good programming practice not to
Dim MyConn, Rs
Set MyConn=Server.CreateObject("ADODB.Connection")
Set Rs=Server.CreateObject("ADODB.RecordSet")
MyConn.Open("cmspl4-access")
Rs.Open "SELECT * From Customer", MyConn, 1, 2
HHL
Crudding with ASP
3
HHL
1.7.
Crudding with ASP
4
In a nutshell
In a nutshell this is what you will learn in this lecture

CREATING records uses code exemplified by
Rs.AddNew
Rs("CustomerTitle")=Request.Form("CustomerTitle")
Rs.Update

The italics refer to
fields
UPDATING records uses code exemplified by
Rs("CustomerTitle")=Request.Form("CustomerTitle")
Rs.Update
This is unlike VBA where we would have had to precede the edits with Rs.Edit

DELETING records uses code exemplified by
Rs.Open "DELETE * From Customer WHERE CustomerNo=" &
Request.QueryString("CustNo"), MyConn, 1, 2

BROWSING records uses code exemplified by
Response.write("<TR>")
While NOT Rs.EOF
FOR i=0 TO Rs.Fields.Count-1
Response.write("<TD>" & Rs(i) & "</TD>")
NEXT
Response.write("</TR>")
Rs.MoveNext
WEND
HHL
Crudding with ASP
This prints out the contents of
each field
4
HHL
Crudding with ASP
5
2. Hello world
ACTIVITY 1a. The objective of this exercise is to make sure that you can get a simple ASP page to
work.
Using Dreamweaver to construct the following, and save as Hello.asp. Put it to a server and then call
it in a browser using something like
http://otho.cms.shu.ac.uk/dbstudents/username/Hello.asp
Use you own url
<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<HTML>
1. Look how VBScript is delimited by
<HEAD>
<%
<TITLE> ASP Page </TITLE>
</HEAD>
%>
<BODY>
2. Notice also the Response object,
<%
which contains the Write method,
Response.Write("Hello World!")
which between them send the
%>
equivalent HTML back to the Web
</BODY>
server and hence to the client.
</HTML>
This then displays
This is the HTML that is sent back to the client (c.f. View-->Source in IE)
<HTML>
<HEAD>
<TITLE> ASP Page </TITLE>
</HEAD>
<BODY>
This is what Response.Write did
Hello World!
</BODY>
</HTML>
ACTIVITY 1b. Create a file called MyMessage.asp that displays on the client a message other than
Hello World!. Save it to a server and call it from a browser. You should thus have practiced a) creating
an asp page on a development machine b) FTP-ing the asp page to a server c) Calling the asp page
from a browser on a client. In your case the development machine and the client are the same machine,
but, of course, they do not have to be.
You should rehearse in your mind what the sequence of events is when you type something like
http://otho.cms.shu.ac/dbstudents/username/Hello.asp in a browser.
HHL
Crudding with ASP
5
HHL
Crudding with ASP
6
The teaching points from those exercises were






asp pages are written inside HTML pages
asp pages run on the server and produce HTML 'on the fly'
asp code is placed between the brackets <% and %>
asp code is interpreted by an asp extension to a webs server (e.g. IIS, Apache, Tomcat)
the asp extension simply passes back any HTML (and anything inside <SCRIPT> tags) back
to the web server
any script that the extension finds will eventually be converted into HTML and sent back to
the Web server. For example, if the extension sees
Response.write("Hello world")
then this is converted into
Hello world
and sent back to the web server
However, as we shall see in a minute, if the extension sees an SQL statement then it has to
converse with the database using whatever drivers that it has been told to use, and eventually send
back HTML to the web server.
HHL
Crudding with ASP
6
HHL
Crudding with ASP
7
3. Passing information from a Form
ACTIVITY 2a. The objective of this exercise is for you to submit a form (from a client to the server)
and report back the contents of the form, and to remind yourself that the contents of most widgets
become available as Request.Form("widgetname") as long as the Form's METHOD is POST
a)
Create a form on the client and save it as FirstASPForm.html
<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<HTML>
<HEAD>
<TITLE> Sending the contents of a form </TITLE>
Use your own
</HEAD>
url
<FORM METHOD="POST"
ACTION="http://otho.cms.shu.ac.uk/dbstudents/username/HandlingFirstForm.asp">
<P> Please input Your First Name:
<BR> <INPUT NAME="FirstName" TYPE="TEXT">
<P> Please Enter Your Last Name:
<BR><INPUT NAME="LastName" TYPE="TEXT">
<INPUT TYPE="SUBMIT" VALUE="Continue">
</FORM>
</HTML>
Run this through a browser and you should see that the only thing wrong is that you have not written
the ASP file on the server.
b) Now we have to write an ASP file and put it on the server.
Construct the following in HandlingFirstForm.asp (and FTP it to the server)
<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<HTML>
<HEAD><TITLE> Registration results </TITLE></HEAD>
<BODY>
Thank you <%=Request.Form("FirstName")%> for registering
The above is the important line. It introduces the Request
object that contains the Form method, which takes one
parameter, which is the name of one of the 'widgets' on the
form.
</BODY>
</HTML>
This is what you should see
HHL
Crudding with ASP
7
HHL
Crudding with ASP
8
and when you press the Continue button, this is what you should see.
This is the HTML produced by the ASP extensions to the Web Server (IIS maybe).
<HTML>
<HEAD><TITLE> Registration results </TITLE></HEAD>
<BODY>
Thank you Hugh for registering
</BODY>
</HTML>
So, the conclusion from that is that the contents of most 'widgets' on a form are obtained by
Request.Form("widgetName") as long as the Form's METHOD is POST.
ACTIVITY 2b. Create two more pages a) one with a form on it with more widgets on it (e.g. a
Textarea box and a drop-down list) b) a page that reports back the contents of the first page
The teaching points from those exercises were
o If a calling Form has a POST method then nearly all 'widget' values become available
via Request.Form("widgetName") in the called page
o Thus pages nearly always go in pairs
o a calling page (often an HTML page)
o a called page, asp in this lecture
HHL
Crudding with ASP
8
HHL
Crudding with ASP
9
4. Browsing a Table
ACTIVITY 3a. The objective of this activity is to Browse a table on the server
I have a database that contains a Table called Customer that has the following structure and data in it
Construct the following and save it as MyBrowseCustomer.asp, and run it.
<html>
<head>
<title> Browsing a database file </title>
</head
<body>
<%
Set MyConn=Server.CreateObject("ADODB.Connection")
Set Rs=Server.CreateObject("ADODB.RecordSet")
MyConn.Open("cmspl4-access")
Rs.Open "SELECT * From Customer", MyConn, 1, 2
Response.write("<TABLE BORDER=1> <TR>")
FOR i=0 TO Rs.Fields.Count-1
Response.write("<TH>" & Rs(i).Name &"</TH>")
NEXT
Response.write("</TR>")
Response.write("<TR>")
While NOT Rs.EOF
FOR i=0 TO Rs.Fields.Count-1
Response.write("<TD>" & Rs(i) & "</TD>")
NEXT
Response.write("</TR>")
Rs.MoveNext
WEND
Response.write("</TABLE>")
%>
</Body>
</html>
HHL
Crudding with ASP
This is where we use the DSN.
PLEASE PUT IN YOUR own
Each student will have to
choose their own Table name
here
This prints out the Field
names as column headers
This prints out the contents of
each field
9
HHL
Crudding with ASP
10
This is what you should see
We need to go through the VBScript line-by-line
<%
Set MyConn=Server.CreateObject("ADODB.Connection")
Set Rs=Server.CreateObject("ADODB.RecordSet")
MyConn.Open("cmspl4-access")
Set up a connection in
MyConn
Set up a Recordset Rs.
A Recordset is a copy of a
subset of database data that is
held in RAM on the server
Set up a DSN connection
Rs.Open "SELECT * From Customer", MyConn, 1, 2Put data into the Recordset that
corresponds to the SQL, using the
connection MyConn. The 1,2 means
"Allow the Recordset to be changed"
(unnecessary in this case)
Response.write("<TABLE BORDER=1> <TR>")
Create some HTML 'on the fly'
FOR i=0 TO Rs.Fields.Count-1
Response.write("<TH>" & Rs(i).Name &"</TH>")
NEXT
Response.write("</TR>")
First of all note VBScript's deterministic loop structure FOR.... NEXT. Recordsets have a number of
methods/attributes associated with them a) Fields, which has an attribute Count b) Name, which holds the
name of the i'th field (with i starting at 0). NOTE that Rs(i) holds the contents of the i'th field.
HHL
Crudding with ASP
10
HHL
Crudding with ASP
11
Response.write("<TR>")
While NOT Rs.EOF
FOR i=0 TO Rs.Fields.Count-1
Response.write("<TD>" & Rs(i) & "</TD>")
NEXT
Response.write("</TR>")
Make sure that you move the Recordset pointer on one
Rs.MoveNext
WEND
NOTE 1. See VBScript's non-deterministic loop structure c.f. While
NOTE 2. Rs(i) holds the contents of the i'th field of the Record that is being pointed at by an invisible
Recordset pointer, which is pointing originally at the 1st record.
Response.write("</TABLE>")
%>
5. Using Other data sources
You have been using the MsAccess database you have stored on your webserver account up to now.
You will of course be aware that Access is not a suitable database for use as the back-end to a webbased database system which may have many concurrent users.
You can however, readily use the friendly Access environment to rapidly prototype a solution, and then
make the relatively minor adjustments to your ASP code required to point at another database, for
example an Oracle instance.
HHL
Crudding with ASP
11
HHL
Crudding with ASP
12
The code below is almost identical to as MyBrowseCustomer.asp we built above. Make sure you
understand what the key differences are. This example also demonstrates using a connection string. Cut
this out and edit the connection string so that it points at the Oracle account you created for yourself
earlier. Save it as EmpBrowse.asp and PUT it to the server.
<html>
<head>
<title> Browsing an Oracle database table </title>
Change UserID and Password to
</head
match your Oracle account
<body>
<%
const connStr = "Provider=OraOLEDB.Oracle;User ID=cmspl4;Password=fleur1;Data
Source=shu10g;"
Set MyConn=Server.CreateObject("ADODB.Connection")
This is slightly different as we
Set Rs=Server.CreateObject("ADODB.RecordSet")
are not using a DSN
MyConn.Open connStr
Rs.Open "SELECT * From emp", MyConn, 1, 2
Response.write("<TABLE BORDER=1> <TR>")
FOR i=0 TO Rs.Fields.Count-1
Response.write("<TH>" & Rs(i).Name &"</TH>")
NEXT
Response.write("</TR>")
Note: No Change to
this code from the
Access version
HHL
Response.write("<TR>")
While NOT Rs.EOF
FOR i=0 TO Rs.Fields.Count-1
Response.write("<TD>" & Rs(i) & "</TD>")
NEXT
Response.write("</TR>")
Rs.MoveNext
WEND
Response.write("</TABLE>")
myConn.close
%>
</Body>
</html>
Crudding with ASP
Emp is a demo table that is
available on most Oracle
databases prior to 10g. You
should have a copy in your
schema.
12
HHL
Crudding with ASP
13
Points to note:
The Data Source parameter could point at any Oracle instance. We only have access to shu10g here. As
an example follow these steps:
1.
Launch SQLPlusw from the start button, or use the Unix or Telnet interface
2.
cut this and drop it on the sql> prompt:
Drop Table Customer ;
Create Table Customer(
CustomerNo Integer Primary Key,
CustomerTitle Varchar2(10),
CustomerFirst Varchar2(30),
CustomerLast Varchar2(30),
CustomerLevel Integer) ;
Insert Into Customer Values(1, 'Mr', 'John', 'Smith', 1) ;
Insert Into Customer Values(2, 'Mrs', 'Joanne', 'Smith', 1) ;
Insert Into Customer Values(3, 'Mr', 'Fred', 'Delus', 3) ;
Insert Into Customer Values(4, 'Dr', 'Cliff', 'Spock', 1) ;
Commit ;
3.
You now have a customer table in your Schema on the shu10g instance.
4.
Try this code (after changing the connection string of course!):
<html>
<head>
<title> Browsing a database file </title>
</head
<body>
<%
const connStr = "Provider=OraOLEDB.Oracle;User ID=cmspl4;Password=fleur1;Data
Source=shu10g;"
Set MyConn=Server.CreateObject("ADODB.Connection")
Set Rs=Server.CreateObject("ADODB.RecordSet")
MyConn.Open connStr
Rs.Open "SELECT * From Customer", MyConn, 1, 2
Response.write("<TABLE BORDER=1> <TR>")
FOR i=0 TO Rs.Fields.Count-1
Response.write("<TH>" & Rs(i).Name &"</TH>")
NEXT
Response.write("</TR>")
Response.write("<TR>")
While NOT Rs.EOF
FOR i=0 TO Rs.Fields.Count-1
Response.write("<TD>" & Rs(i) & "</TD>")
NEXT
Response.write("</TR>")
Rs.MoveNext
WEND
Response.write("</TABLE>")
myConn.close
HHL
Crudding with ASP
13
HHL
Crudding with ASP
14
%>
</Body>
</html>
ACTIVITY 3b. Write a page that has on it a drop-down list of Tables in a database and calls a
browsing page that displays all the fields and all the records of the chosen Table. Start by displaying
the tables in your Access database.
Note: 3b needs you to use the OpenSchema method. This is a good opportunity to begin using the web
to give you extra information. The link to the MSDN is a good start!
Now repeat this for your Oracle tables. Although OpenSchema would work, you could use the Oracle
supplied View "Tab" which lists just the tables owned by you. This will save you filtering out System
Tables. (Hint:Try:
select * from tab
from the Oracle SQLPlus sql> prompt and see what column names are output)
The teaching points from those exercises were
o
o
o
A Recordset is a copy, in RAM, of database Table or query
A Data Source Name (DSN) is a pointer to a database
We have to create a connection, create a database, open the connection (using a DSN) and run
some SQL
Set MyConn=Server.CreateObject("ADODB.Connection")
Set Rs=Server.CreateObject("ADODB.RecordSet")
MyConn.Open("DSN")
Rs.Open "SELECT * From Customer", MyConn, 1, 2
o
To output field names use
FOR i=0 TO Rs.Fields.Count-1
Response.write("<TH>" & Rs(i).Name &"</TH>")
NEXT
o
To output field values use
FOR i=0 TO Rs.Fields.Count-1
Response.write("<TD>" & Rs(i) & "</TD>")
NEXT
o
To move through a Recordset use
While NOT Rs.EOF
...........
...........
Rs.MoveNext
WEND
o
HHL
Other ways of moving the Recordset pointer are MoveFirst, MoveLast, MovePrevious
(Note that the pointer is placed on the 1st record when you open a Recordset)
Crudding with ASP
14
HHL
Crudding with ASP
15
6. Creating a record
Using AddNew
One Recordset Object has a method called AddNew, which allows records added to the recordset to be
posted back to the underlying database.
ACTIVITY 4a. The objective of this exercise is to get some information from a form and put it in a
database on the server.
a) Put the following in Act4a.asp
<HTML>
<HEAD>
Use your own url
<TITLE> Create a record</TITLE>
</HEAD>
<FORM METHOD="POST"
ACTION="http://otho.cms.shu.ac.uk/dbstudents/username/Act4aHandler.asp">
Please Enter Your Title:
<INPUT NAME="CustomerTitle" TYPE="TEXT"> <BR>
Please Enter Your User level:
<INPUT NAME="CustomerLevel" TYPE="TEXT"> <BR>
Please Enter Your First Name:
<INPUT NAME="CustomerFirstName" TYPE="TEXT"> <BR>
Please Enter Your Surname:
<INPUT NAME="CustomerSurname" TYPE="TEXT"> <BR>
<INPUT TYPE="Reset" >
<INPUT TYPE="SUBMIT" VALUE="Continue">
</FORM>
</HTML>
HHL
Crudding with ASP
15
HHL
Crudding with ASP
16
b) Put the following in Act4ahandler.asp
<html>
<head>
<title> Handling Create a record </title>
</head>
<body>
<%
Set MyConn=Server.CreateObject("ADODB.Connection")
Set Rs=Server.CreateObject("ADODB.RecordSet")
MyConn.Open("cmspl4-access")
Rs.Open "SELECT * From Customer", MyConn, 1, 2
Response.write("<BR> You Typed " &Request.Form("CustomerTitle") & " " &
Request.Form("CustomerLevel")& " " & Request.Form("CustomerFirstName")&
Request.Form("CustomerSurName")& "<BR>")
Rs.AddNew
Rs("CustomerTitle")=Request.Form("CustomerTitle")
Rs("CustLevel")=Request.Form("CustomerLevel")
Rs("CustFirstName")=Request.Form("CustomerFirstName")
Rs("CustSurname")=Request.Form("CustomerSurname")
Rs.Update
Response.write("<H1>Record Added</H1><BR>")
Rs.Close
%>
</body>
</html>
This is what you should see when you run Act4a.asp
You can check whether it works by running the browsing AS that you wrote in Activity 3
HHL
Crudding with ASP
16
HHL
Crudding with ASP
17
Using INSERT
Using the AddRecord method is only appropriate when you already have the recordset. You may want
to insert data without managing the dataset locally. In such circumstances you can simply call the
connection object's Execute method to run an SQL Insert statement.
Follow these steps:
1) Copy your code from Act4a.html above and save it as Act4a_insert.html
2) Amend the form's ACTION to read:
ACTION="http://otho.cms.shu.ac.uk/dbstudents/username/Act4aHandler_Insert.asp"
>
3) Create Act4aHandler_Insert.asp with the code below
4) PUT these to your website
Code for Act4aHandler_Insert.asp:
<html>
<head>
<title> Handling Create a record Using Insert </title>
</head>
<body>
<%
Dim sql
Set MyConn=Server.CreateObject("ADODB.Connection")
Set Rs=Server.CreateObject("ADODB.RecordSet")
MyConn.Open("cmspl4-access")
Build the INSERT command
sql = "insert into Customer (CustomerTitle, CustLevel, CustFirstName, CustSurname)
values ('" & _
Request.Form("CustomerTitle") & "', '" & Request.Form("CustomerLevel") & "', '" &
Request.Form("CustomerFirstName") & "', '" & Request.Form("CustomerSurname") & "')"
MyConn.Execute sql
Execute the INSERT command
Response.write("<BR> You Typed " &Request.Form("CustomerTitle") & " " &
Request.Form("CustomerLevel")& " " & Request.Form("CustomerFirstName")&
Request.Form("CustomerSurName")& "<BR>")
MyConn.Close
Set MyConn = Nothing
The Close method closes a recordset and
frees any associated system resources.
However to remove an object from
memory set Recordset object to Nothing
%>
</body>
</html>
HHL
Crudding with ASP
17
HHL
Crudding with ASP
18
ACTIVITY 4b. Create 2 new that take information from a calling page (that contains lots of widgets)
and puts that information into the Oracle database.
The teaching points from those exercises were


Rs.Addnew creates a 1 record buffer in RAM that contains all the fields of Rs
Rs.Update writes the buffer to the database
For example
Rs.AddNew
Rs("CustomerTitle")=Request.Form("CustomerTitle")
Rs("CustLevel")=Request.Form("CustomerLevel")
Rs("CustFirstName")=Request.Form("CustomerFirstName")
Rs("CustSurname")=Request.Form("CustomerSurname")
Rs.Update
When adding a new record be careful not to write to Autonumber fields (in MS Access). The same idea
applies to Oracle where you could have a trigger on a Table that is fired when an insert is performed
and this runs a sequence object.

HHL
You can issue SQL commands, such as INSERT
Crudding with ASP
18
HHL
Crudding with ASP
19
7. Updating a Record
We are going to create 3 pages
a) Act5aSelect.asp
b) Act5aUpdate.asp
c) Act5aHandler.asp
where we show a few fields of the Customer Table.
We then click on CustomerNo and this calls
Act5aUpdate.asp and we pass to it
CustomerNo in a QueryString
where we show all the fields of the record selected in
Act5aSelect.asp and allow all fields
(except CustomerNo ) to be updated in a Form.
When we press the Submit button, this calls
Act5aHandler.asp that writes the
information from the Form to the database
Writes to the database and allows the user to see the effect
by calling MyBrowseCustomer.asp
So, Diagrammatically we have
SelectARecord
UpdateARecord
HandleUpdateARecord
BrowseCustomer
HHL
Crudding with ASP
19
HHL
Crudding with ASP
20
ACTIVITY 5a. We are now going to create those 3 pages
a) Creating Act5aSelect.asp
<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<% Option Explicit %>
<html>
<head>
<title> Selecting a Record </title>
</head
><body>
<%
Dim MyString, MyConn,Rs
Set MyConn=Server.CreateObject("ADODB.Connection")
Set Rs=Server.CreateObject("ADODB.RecordSet")
MyConn.Open("cmspl4-access")
Rs.Open "SELECT * From Customer", MyConn, 1, 2
Response.write("<TABLE BORDER=1> <TR>")
Response.write("<TH>" & "CustomerNo" &"</TH>")
Response.write("<TH>" & "Title" &"</TH>")
Response.write("<TH>" & "FirstName" &"</TH>")
Response.write("<TH>" & "Surname" &"</TH>")
Response.write("</TR>")
Use you own DSN
This is simply writing out some
table headers
While NOT Rs.EOF
Response.write("<TR>")
MyString="<a HREF=Act5aUpdate.asp?CustomerNo=" & Rs("CustomerNo") & ">" &
Rs("CustomerNo") & "</a>"
Response.write("<TD>" & MyString & "</TD>")
This is writing out the contents
Response.write("<TD>" & Rs("CustomerTitle" ) & "</TD>")
of a few fields of the record
Response.write("<TD>" & Rs("CustFirstName" ) & "</TD>")
currently being pointed at
Response.write("<TD>" & Rs("CustSurname" ) & "</TD>")
Response.write("</TR>")
Rs.MoveNext
WEND
Response.write("</TABLE>")
%>
</Body>
</html>
So, there is only one hard line is the above which is highlighted. All it is trying to do is to make
CustomerNo clickable and call Act5Update.asp with the querystring variable CustoNo set to the
CustomerNo of the record that we are on. So what is produced is something like
<a HREF=Act5aUpdate.asp?CustNo=5>5</a>
You should see something like this
HHL
Crudding with ASP
20
HHL
Crudding with ASP
21
b) Creating Act5aUpdate.asp
<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<% Option Explicit %>
<html>
<head>
<title>Updating a Record</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<%
Dim MyConn,Rs
Set MyConn=Server.CreateObject("ADODB.Connection")
Set Rs=Server.CreateObject("ADODB.RecordSet")
MyConn.Open("cmspl4-access")
Rs.Open "SELECT * From Customer WHERE CustomerNo=" &
Request.QueryString("CustomerNo"), MyConn, 1, 2
%>
Note:
Hidden
field
<form name="form1" method="post" action="Act5ahandler.asp">
<input name="CustomerNo" type="hidden" id="CustomerNo"
value=<%=Rs("CustomerNo")%>>
<table width="75%" border="1">
<tr>
<td><strong>Customer Title</strong></td>
<td><input name="CustTitle" type="text" id="CustTitle"
value=<%=Rs("CustomerTitle")%>></td>
</tr>
<tr>
<td><strong>Customer First Name</strong></td>
<td><input name="CustFirstName" type="text" id="CustFirstName"
value=<%=Rs("CustFirstName" )%>></td>
</tr>
<tr>
<td><strong>Customer Surname</strong></td>
<td><input name="CustSurname" type="text" id="CustSurname"
value=<%=Rs("CustSurname" )%>></td>
</tr>
<tr>
<td><strong>Customer Level</strong></td>
<td><input name="CustLevel" type="text" id="CustLevel"
value=<%=Rs("CustLevel")%>></td>
</tr>
<tr>
HHL
Crudding with ASP
This is where we use
the QueryString
All the rest of it is doing is
ouputting all the fields of the
chosen record neatly into a
table
NOTE.
Rs("CustomerTitle") will
yield the value of the
CustomerTitle field of the
record currently being pointed
to.
21
HHL
Crudding with ASP
22
<td><strong>Customer Address</strong></td>
<td><input name="CustAdd1" type="text" id="CustAdd1"
value=<%=Rs("CustAdd1")%>></td>
</tr>
<tr>
<td> </td>
<td><input name="CustAdd2" type="text" id="CustAdd2"
value=<%=Rs("CustAdd2")%>></td>
</tr>
<tr>
<td> </td>
<td><input name="CustAdd3" type="text" id="CustAdd3"
value=<%=Rs("CustAdd3")%>></td>
</tr>
<tr>
<td><strong>Customer Billing Address</strong></td>
<td><input name="CustBill1" type="text" id="CustBillAdd1"
value=<%=Rs("CustBillAdd1")%>></td>
</tr>
<tr>
<td> </td>
<td><input name="CustBill2" type="text" id="CustBillAdd2" value=<%=Rs("CustBillAdd2"
)%>></td>
</tr>
<tr>
<td> </td>
<td><input name="CustBill3" type="text" id="CustBillAdd3"
value=<%=Rs("CustBillAdd3")%>></td>
</tr>
<tr>
<td><strong>Tel:</strong></td>
<td><input name="CustTel" type="text" id="CustTel" value=<%=Rs("CustTel")%>></td>
</tr>
<tr>
<td><strong>Direct Tel:</strong></td>
<td><input name="CustDirectTel" type="text" id="CustDirectTel"
value=<%=Rs("CustDirectTel")%>></td>
</tr>
<tr>
<td><strong>Fax:</strong></td>
<td><input name="CustFax" type="text" id="CustFax" value=<%=Rs("CustFax"
)%>></td>
</tr>
<tr>
<td><strong>e-mail</strong></td>
<td><input name="CustEMail" type="text" id="CustEMail"
value=<%=Rs("CustEMail")%>></td>
</tr>
</table>
<p>
<input type="submit" name="Submit" value="Submit">
</p>
</form>
<p> </p>
</body>
</html>
HHL
Crudding with ASP
22
HHL
Crudding with ASP
23
So, you should see something like this when a CustomerNo is pressed on Act5aSelect.asp
We can now modify this record (but not CustomerNo) and press Submit which will call
Act5aHandler.asp
c) Creating Act5aHandler.asp
<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<% Option Explicit
Dim MyConn, Rs
Set MyConn=Server.CreateObject("ADODB.Connection")
Set Rs=Server.CreateObject("ADODB.RecordSet")
MyConn.Open("cmspl4-access")
Response.write("Connection open")
Rs.Open "SELECT * From Customer WHERE CustomerNo=" &
Request.Form("CustomerNo"), MyConn, 1, 2
Rs("CustomerTitle")=Request.Form("CustTitle")
Rs("CustLevel")=Request.Form("CustLevel")
Rs("CustFirstName")=Request.Form("CustFirstName")
Rs("CustSurname")=Request.Form("CustSurname")
Rs("CustAdd1")=Request.Form("CustAdd1")
Rs("CustAdd2")=Request.Form("CustAdd2")
Rs("CustAdd3")=Request.Form("CustAdd3")
Rs("CustBillAdd1")=Request.Form("CustBillAdd1")
Rs("CustBillAdd2")=Request.Form("CustBillAdd2")
Rs("CustBillAdd3")=Request.Form("CustBillAdd3")
Rs("CustTel")=Request.Form("CustTel")
Rs("CustDirectTel")=Request.Form("CustDirectTel")
Rs("CustTel")=Request.Form("CustTel")
Rs("Custemail")=Request.Form("Custemaill")
Rs("CustFax")=Request.Form("CustFax")
HHL
Crudding with ASP
This is simply replacing field
values with values passed from
a calling form
23
HHL
Crudding with ASP
Rs.Update
Rs.Close
Response.Redirect("MyBrowseCustomer.asp")
%>
24
Don't forget to write to the database
ACTIVITY 5b. Modify Activity 5a so that it works with any table.
The teaching points from those exercises were
 To make some text clickable that calls another asp page and passes to it some data via
QueryString use something like this
MyString="<a HREF=UpdateARecord.asp?CustNo=" & Rs("CustomerNo") & ">" &
Rs("CustomerNo") & "</a>"
Response.write("<TD>" & MyString & "</TD>")
This produces something like this <a HREF=UpdateARecord.asp?CustNo=5>5</a>

To use a value passed as a Query string use something like this
Rs.Open "SELECT * From Customer WHERE CustomerNo=" &
Request.QueryString("CustNo"), MyConn, 1, 2

To open another page use something like this
Response.Redirect("MyBrowseCustomer.asp")

Hidden fields are often a convenient way of passing information from page to page
<input name="CustomerNo" type="hidden" id="CustomerNo"
value=<%=Rs("CustomerNo")%>>
HHL
Crudding with ASP
24
HHL
Crudding with ASP
25
8. Deleting a record
We are going to create 2 pages
a) Act6aSelect.asp
which will ask us if we really want to delete and
then will call Act6aHandler.asp. You will see
that Act6aSelect.asp is very like
Act5aSelect
b) Act6aHandler.asp
calls
which simply deletes the selected record and
MyBrowseCustomer.asp
CustomerNo passed as a QueryString in the
QueryString variable CustNo
So, diagrammatically we have
SelectForDelete
MyBrowseCustomer.asp
HandleDelete.asp
ACTIVITY 6a. We are now going to create these 2 pages
a) Creating Act6aSelect.asp
<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<% Option Explicit %>
<html>
<head>
<title> Selecting a Record for Deletion</title>
<SCRIPT Language="Javascript">
function MyClick(MyCustomerNo)
{
var myString
This is a bit of Javascript that asks the user "Are you
sure that you want to delete?" and if yes, opens up
Act6aHandler.asp and passes to it the CustomerNo
via a QueryString
myString="http://otho.cms.shu.ac.uk/dbstaff/cmspl4/crud/Act6aHandler.asp?CustNo="
+ MyCustomerNo
if(prompt("Are you sure that you want to delete this record: "+MyCustomerNo
,"Yes"))
{
window.open(myString)
}
}
</SCRIPT>
Use your own URL
</head
><body>
<%
Dim MyString, MyConn,Rs
Set MyConn=Server.CreateObject("ADODB.Connection")
HHL
Crudding with ASP
25
HHL
Crudding with ASP
26
Set Rs=Server.CreateObject("ADODB.RecordSet")
MyConn.Open("cmspl4-access")
Rs.Open "SELECT * From Customer", MyConn, 1, 2
Response.write("<TABLE BORDER=1> <TR>")
Response.write("<TH>" & "CustomerNo" &"</TH>")
Response.write("<TH>" & "Title" &"</TH>")
Response.write("<TH>" & "FirstName" &"</TH>")
Response.write("<TH>" & "Surname" &"</TH>")
Response.write("</TR>")
The OnClick event handler
While NOT Rs.EOF
Response.write("<TR>")
MyString="<a OnClick=MyClick(" & Rs("CustomerNo") & ")><u>" & Rs("CustomerNo") &
"</u></a>"
Response.write("<TD>" & MyString & "</TD>")
Response.write("<TD>" & Rs("CustomerTitle" ) & "</TD>")
Response.write("<TD>" & Rs("CustFirstName" ) & "</TD>")
Response.write("<TD>" & Rs("CustSurName" ) & "</TD>")
Response.write("</TR>")
Rs.MoveNext
WEND
Response.write("</TABLE>")
%>
</Body>
</html>
This what you should see when record 24 is
selected
HHL
Crudding with ASP
26
HHL
Crudding with ASP
27
b)
All this does is to run some SQL that
<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
deletes the chosen record and then calls
<% Option Explicit %>
MyBrowseCustomer.asp
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<%
Dim MyString, MyConn,Rs
Set MyConn=Server.CreateObject("ADODB.Connection")
Set Rs=Server.CreateObject("ADODB.RecordSet")
MyConn.Open("cmspl4-access")
Rs.Open "DELETE * From Customer WHERE CustomerNo=" &
Request.QueryString("CustNo"), MyConn, 1, 2
Response.Redirect("MyBrowseCustomer.asp")
%>
</body>
</html>
Use your own
ACTIVITY 6b. Modify Activity 6a so that it works on any Table.
The teaching points from those exercises were
 Javascript inside <SCRIPT> </SCRIPT> tags is ignored by the asp extension and is passed
straight back to the Web server untouched. So, the Javascript will run on the client.
 So, as well as generating HTML 'on the fly' we can generate Javascript 'on the fly'
 In order to delete records in asp pages we simply run a DELETE statement in SQL.
e.g:
Rs.Open "DELETE * From Customer WHERE CustomerNo=" &
HHL
Crudding with ASP
Request.QueryString("CustNo"), MyConn, 1, 2
27
HHL
Crudding with ASP
28
9. Summary


We showed how to 'crud' (i.e. CReate, Update and Delete) records from a Table using
VBScript in asp pages. We also showed how to Browse records in a Table.
We introduced the concept of a Recordset, which is a copy in RAM of a database table, or
query.
o Connections to a database are created with
Set MyConn=Server.CreateObject("ADODB.Connection")
o Recordsets are created with Set Rs=Server.CreateObject("ADODB.RecordSet")
o Connections are opened with MyConn.Open("DSN")
o SQL is executed with Rs.Open "SELECT * From Customer", MyConn, 1, 2
o To move the Recordset pointer through a Recordset we use
While NOT Rs.EOF
....................
....................
....................
Rs.MoveNext
WEND
o To move the Recordset pointer we use MoveFirst, MoveLast, MoveNext,
MovePrevious
o To output field names we use
FOR i=0 TO Rs.Fields.Count-1
Response.write("<TH>" & Rs(i).Name &"</TH>")
NEXT
o To output field values we use
FOR i=0 TO Rs.Fields.Count-1
Response.write("<TD>" & Rs(i) & "</TD>")
NEXT
or we can use Rs("CustomerNo")

We used DSN connections and started off our asp pages with
Option Explicit
Dim MyConn, Rs
Set MyConn=Server.CreateObject("ADODB.Connection")
Rs.Open "SELECT * From Customer", MyConn, 1, 2

CREATING records uses code exemplified by
Rs.AddNew
Rs("CustomerTitle")=Request.Form("CustomerTitle")
Rs("CustLevel")=Request.Form("CustomerLevel")
Rs("CustFirstName")=Request.Form("CustomerFirstName")
Rs("CustSurname")=Request.Form("CustomerSurname")
Rs.Update

The italics refer to
fields
UPDATING records uses code exemplified by
Rs("CustomerTitle")=Request.Form("CustomerTitle")
Rs("CustLevel")=Request.Form("CustomerLevel")
Rs("CustFirstName")=Request.Form("CustomerFirstName")
HHL
Crudding with ASP
28
HHL
Crudding with ASP
29
Rs("CustSurname")=Request.Form("CustomerSurname")
Rs.Update
This is unlike VBA where we would have had to precede the edits with Rs.Edit

DELETING records uses code exemplified by
Rs.Open "DELETE * From Customer WHERE CustomerNo=" &
Request.QueryString("CustNo"), MyConn, 1, 2

BROWSING records uses code where we create a table and in it write information from the
database using statements like
Response.write("<TR>")
While NOT Rs.EOF
FOR i=0 TO Rs.Fields.Count-1
Response.write("<TD>" & Rs(i) & "</TD>")
NEXT
Response.write("</TR>")
Rs.MoveNext
WEND
This prints out the contents of
each field

We used 3 methods of passing information between pages viz
o Request.Form
o Request.QueryString
o Request.Form using a hidden field

Javascript inside <SCRIPT> </SCRIPT> tags is ignored by the asp extension and is passed
straight back to the Web server untouched.
HHL
Crudding with ASP
29
HHL
Crudding with ASP
30
.
10.
References
10.1.
Books
"Active Server Pages Bible" by Eric A. Smith. Published by IDG books 2000. ISBN 0-7645-4599-X
10.2.
Web-sites
This has a directory of tutorials
http://www.aspin.com/
HHL
Crudding with ASP
30
HHL
11.
Crudding with ASP
31
Self-Test
1. What is a Recordset?
2. How do you connect to a server?
3. How do you create a Recordset?
4. How do you loop through a Recordset?
5. How do you send the information from a Recordset to a database?
6. Would we have used the same code for connecting to a) a MySQL database b) an Oracle database c)
an SQL Server 2000 database?
7. How do you call an asp page from an asp page?
8. How are the values of 'widgets' passed from an HTML page to an asp page?
9. Does the answer to question 8. depend on what METHOD is used on the calling page?
10. What is the general code for creating records?
11. What is the general code for updating records?
12. What is the general code for deleting records?
13. What is the general code for browsing records?
14. What happens to Javascript/VBScript inside <SCRIPT></SCRIPT> tags?
15. How do you find out (in VBScript) how many columns there are in recordset?
16. How do you output the names of columns of a recordset?
17. What is a DSN?
18. How are DSNs set up?
19. Is sending information via QueryString inherently more secure than sending it via a Form and the
POST METHOD? In order to answer this you might like to include an error on the called form and see
what the ASP Extension reports.
20. How useful/secure is the use of hidden fields?
21. In MS Access we designed (very easily) 1:m Forms. Discuss how this same functionality could be
achieved using asp pages.
22. Dreamweaver MX makes much easier the production of much of the code that we have produced
here. Discuss whether this lecture has been a waste of time.
HHL
Crudding with ASP
31
HHL
Crudding with ASP
32
12. Suggested Solution to Activity 3b
Activity 3b
The Calling Form:
<html>
<head>
<title>Drop-down List of Tables</title>
</head>
<body>
<form name="form1" method="post"
action="http://otho.cms.shu.ac.uk/dbstaff/cmspl4/crud/ListContents.asp">
<p><strong>Choose a Table</strong>
<select name="Tabl" size="1">
<%@Language=VBScript %>
<%
'parameter to be passsed to OpenSchema to get tablenames
Const adSchemaTables = 20
Set MyConn=Server.CreateObject("ADODB.Connection")
MyConn.Open("cmspl4-access")
Set Rs = MyConn.OpenSchema (adSchemaTables)
20 gets list of tables. Check msdn
site for other values that could be
useful
This is the key bit: opening the
database schema
' note we get all tables, including system ones so filter them out with the If block
Do While Not Rs.EOF
IF Rs ("TABLE_TYPE") <> "SYSTEM TABLE" Then
response.write "<OPTION>" & Rs ("TABLE_NAME") & "</OPTION>"
End If
Rs.MoveNext
Dynamic build of the html tag
Loop
%>
</select>
</p>
<p>
<input type="submit" name="Submit" value="Submit">
<input type="reset" name="Submit2" value="Reset">
</p>
</form>
<br>
</body>
</html>
The Called Form:
<html>
<head>
<title> Browsing a database file - Dynamic version </title>
</head
<body>
<%
Set MyConn=Server.CreateObject("ADODB.Connection")
Set Rs=Server.CreateObject("ADODB.RecordSet")
HHL
Crudding with ASP
32
HHL
Crudding with ASP
33
MyConn.Open("cmspl4-access")
Rs.Open "SELECT * From " & Request.Form("Tabl"), MyConn, 1, 2
Response.write("<TABLE BORDER=1> <TR>")
FOR i=0 TO Rs.Fields.Count-1
Response.write("<TH>" & Rs(i).Name &"</TH>")
NEXT
Response.write("</TR>")
Response.write("<TR>")
While NOT Rs.EOF
FOR i=0 TO Rs.Fields.Count-1
Response.write("<TD>" & Rs(i) & "</TD>")
NEXT
Response.write("</TR>")
Rs.MoveNext
WEND
Response.write("</TABLE>")
%>
</Body>
</html>
The Oracle Version, using select * from tab:
<html>
<head>
<title>Drop-down List of Tables</title>
</head>
<body>
<form name="form1" method="post"
action="http://otho.cms.shu.ac.uk/dbstaff/cmspl4/crud/O_ListContents.asp">
<p><strong>Choose a Table</strong>
<select name="Tabl" size="1">
<%@Language=VBScript %>
<%
const connStr = "Provider=OraOLEDB.Oracle;User ID=cmspl4;Password=fleur1;Data
Source=shu10g;"
Set MyConn=Server.CreateObject("ADODB.Connection")
Set Rs=Server.CreateObject("ADODB.RecordSet")
MyConn.Open connStr
' by selecting against the Oracle provided Tab view, we automatically filter out unwanted tables
' so now we dont need OpenSchema
Rs.Open "SELECT TName From Tab" , MyConn, 1, 2
Do While Not Rs.EOF
response.write "<OPTION>" & Rs ("TNAME") & "</OPTION>"
Rs.MoveNext
Loop
%>
</select>
</p>
<p>
<input type="submit" name="Submit" value="Submit">
<input type="reset" name="Submit2" value="Reset">
</p>
HHL
Crudding with ASP
33
HHL
Crudding with ASP
34
</form>
<br>
</body>
</html>
The called form will need altering slightly:
const connStr = "Provider=OraOLEDB.Oracle;User ID=cmspl4;Password=fleur1;Data
Source=shu10g;"
Set MyConn=Server.CreateObject("ADODB.Connection")
Set Rs=Server.CreateObject("ADODB.RecordSet")
MyConn.Open connStr
In stead of:
Set MyConn=Server.CreateObject("ADODB.Connection")
Set Rs=Server.CreateObject("ADODB.RecordSet")
MyConn.Open("cmspl4-access")
HHL
Crudding with ASP
34
HHL
Crudding with ASP
35
13. Tutorial
1. Write a page that browses a few records (say 5) of a few fields (say 4, including CustomerNo) of
the Customer Table. CustomerNo is to be clickable
The page should have images/text on it for
Move To First Record
Move to Previous Record
Move To Last Record
Move to Next Record
.
2. Modify MyBrowseCustomer.asp so that images can be displayed.
HINT . If you are using an MS Access database modify the Customer Table to have a column
URLOfPicture (of type Text) and use code based on below where we are outputting the contents of
fields
If InStr(RS(i).Name, "URL") > 0 Then
Response.Write( "<img src=""" & RS(i) & """>")
Else
Response.write(Rs(i))
End If
Put some images into the images folder and make the field URLOfPicture point to them as
exemplified below
Customer No
Password
URLofPicture
images/bezad.jpg
images/bernard.jpg
images/fraz.jpg
images/hugh1.jpg
images/joseph.jpg
images/kate.jpg
images/michael1.jpg
images/sanaz.jpg
HHL
Crudding with ASP
35
HHL
Crudding with ASP
36
3. a) You should go to http://www.bitproducts.com/aspcdescription.asp and see if you can do all that
we have done in this lecture in a much simpler way.
b) Same for http://www.aspgrid.com/
c) Same for http://www.visualasp.com/
HHL
Crudding with ASP
36
Download