0% found this document useful (0 votes)
118 views44 pages

Active Server Pages

Active Server Pages (ASP) is a Microsoft technology that allows web pages to dynamically generate HTML content based on server-side scripts. ASP files have the .asp file extension and contain both HTML markup and script code surrounded by <% and %> tags. When an ASP file is requested, the server executes any script code to dynamically output content, which is then returned to the browser as a standard HTML page. Common uses of ASP include dynamically displaying content from a database and creating personalized web pages based on user input. The default scripting language in ASP is VBScript.

Uploaded by

Vinitha Arun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
118 views44 pages

Active Server Pages

Active Server Pages (ASP) is a Microsoft technology that allows web pages to dynamically generate HTML content based on server-side scripts. ASP files have the .asp file extension and contain both HTML markup and script code surrounded by <% and %> tags. When an ASP file is requested, the server executes any script code to dynamically output content, which is then returned to the browser as a standard HTML page. Common uses of ASP include dynamically displaying content from a database and creating personalized web pages based on user input. The default scripting language in ASP is VBScript.

Uploaded by

Vinitha Arun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Active Server Pages

Active Server Pages (ASP) is a Microsoft technology for generating


dynamic HTML content. Dynamic content is content that changes based on
user input and on the instructions you provide in the ASP code. ASP is ideal
for creating web pages customized for different types of users, as well as for
web sites that allow a user to browse and perform actions on records in a
database. ASP is not a standalone technology; rather, ASP files are essentially
HTML files with server scripts included to create and handle dynamic content.
You use a scripting language, such as VBScript (the default scripting language)
or JavaScript, to write the functions and procedures that the application (web
site) will use.

Active Server Pages (ASPs) are Web pages that contain server-side
scripts in addition to the usual mixture of text and HTML (Hypertext Markup
Language) tags. Server-side scripts are special commands you put in Web
pages that are processed before the pages are sent from your Personal Web
Server to the Web browser of someone who's visiting your Web site. . When
you type a URL in the Address box or click a link on a Web page, you're asking
a Web hosting server on a computer somewhere to send a file to the Web
browser (sometimes called a "client") on your computer. If that file is a
normal HTML file, it looks exactly the same when your Web browser receives
it as it did before the Web server sent it. After receiving the file, your Web
browser displays its contents as a combination of text, images, and sounds.

In the case of an Active Server Page, the process is similar, except


there's an extra processing step that takes place just before the Web server
sends the file. Before the Web server sends the Active Server Page to the Web
browser, it runs all server-side scripts contained in the page. Some of these
scripts display the current date, time, and other information. Others process
information the user has just typed into a form, such as a page in the Web
site's guestbook.

To distinguish them from normal HTML pages, Active Server Pages are
given the ".asp" extension.

 ASP is a program that runs inside a web server

1
What is an ASP File?

 An ASP file has the file extension ".asp"


 An ASP file is just the same as an HTML file
 An ASP file can contain server scripts in addition to HTML
 Server scripts in an ASP file are executed on the server

What can ASP do for you?

 Edit, change, add content, or customize any web page


 Respond to user queries or data submitted from HTML forms
 Access databases or other server data and return results to a browser
 Provide web security since ASP code cannot be viewed in a browser
 Offer simplicity and speed

ASP Uses VBScript

The default scripting language in ASP is VBScript.

A scripting language is a lightweight programming language.

VBScript is a light version of Microsoft's Visual Basic.

ASP Files

 ASP files can be ordinary HTML files. In addition, ASP files can also
contain server scripts.
 Scripts surrounded by <% and %> are executed on the server.
 The Response.Write() method is used by ASP to write output to HTML.

The following example writes "Hello World" into HTML:

<!DOCTYPE html>
<html>
<body>
<%
Response.Write("Hello World!")
%>
</body>
</html>
VBScript is case insensitive. Response.Write() can be written as
response.write().

2
Using JavaScript in ASP

To set JavaScript as the scripting language for a web page you must insert a
language specification at the top of the page:

<%@ language="javascript"%>
<!DOCTYPE html>
<html>
<body>
<%
Response.Write("Hello World!")
%>
</body>
</html>

There is an easy shortcut to Response.Write(). You can use an equal sign (=)
instead.

The following example also writes "Hello World" into HTML:

<!DOCTYPE html>
<html>
<body>
<%
="Hello World!"
%>
</body>
</html>

HTML attributes can be a part of the output:

<!DOCTYPE html>
<html>
<body>
<%
Response.Write("<p style='color:#0000ff'>This text is styled.</p>")
%>
</body>
</html>
What Do Server-Side Scripts Look Like?

Server-side scripts look a lot like HTML tags. However, instead of starting and
ending with lesser-than ( < ) and greater-than ( > ) brackets, they typically
start with <% and end with %>. The <% is called an opening tag, and the %> is
called a closing tag. In between these tags are the server-side scripts. You can
insert server-side scripts anywhere in your Web page--even inside HTML tags.

3
How ASP works? The below is the process:

1. The Web browser sends a request to your web server asking for a page.

2. The Web server loads the page and looks for ASP code to run.

3. If ASP code is found, the web server runs the code and sends the results
to the Web browser. So the result page on the client side looks like a
pure HTML page.

You may wonder why we need an ASP page to display web contents while we
have HTML. Well, HTML can be used to display web contents, but the page is
static, not dynamic. Image you have a website that sells products, and you
want to display the name, price, description and category of each product on a
page. Normally in HTML you would have to write this page out by hand, and
every time you change products or prices you would have to go back and re-
write the page. But if you use ASP, you can select records from a database and
generate the HTML page when an user requests it. When you get a new
product or change the prices you will only have to change the information in
the database and the page will automatically be updated to reflect those
changes without writing a single line of code.

ASP Code

When writing ASP you don't need to worry about changing all your HTML, you
simply add ASP code into your HTML pages where needed. YOu also don't
need any special software on your computer, a simple text editor will do. To
begin an ASP page you will first need to tell it what language you have written
it in. The most common (and the one used in this tutorial) is VBScript. You
should begin your page with:

<%@ Language=VBScript %>

All this code does is tell the ASP system that you are writing your page in
VBScript. You will notice that the ASP code is enclosed in special tags. All ASP
code should be enclosed in the 'percent sign tags' in the form:

<% ASP Code Here %>

4
Code can be written over multiple lines, but any code not enclosed in the ASP
tags will simply be treated as HTML. Similarly and HTML inside these tags but
not specifically sent as output by the code will cause an error.

Sending Output To The Browser

Sending output is done using the ASP command:

Response.Write()
so to write 'Hello World' to the user's browser the complete code would be:
<%@ Language=VBScript %>

<% Response.Write("Hello World") %>

Again, this code begins by telling the system that you are writing in VBScript.
Then comes the Response.Write command. Basically this is made up of two
parts. 'Response' tells the server that you want to send information to the
user. There are other types of command including: Request (which gets
information from the user), Session (for user session details), Server (for
controlling the server) and Application (for commands relating to the
application). More about these later.

The second part, 'Write', tells the server that the type of response you would
like to send is to write information to the user's browser. This doesn't just
have to be text, but can include variables, which will be discussed in more
depth later in this tutorial.

Variables
Probably the most important feature of a programming language is a variable.
A variable is basically a way of storing text, numbers or other data, so that it
can be referenced later. For example, to change the earlier 'Hello World'
script:

<%@ Language=VBScript %>


<%
OutputText = "Hello World"
Response.Write(OutputText)
%>
The output of this code will be exactly the same as the first script, but it is
fundementally different as it uses variables. Basically what this code does
follows:
OutputText = "Hello World"

5
This line sets up a variable called OutputText and stores in it the string of
letters 'Hello World'.

As this is now stored in a variable, you can now reference this text you have
stored in any part of your script, and you can also manipulate it. The next line:

Response.Write(OutputText)
tells the server that you are sending information to the browser, and that the
information to be sent is the contents of the variable called OutputText. Please
note that the variable name is not enclosed in quotation marks. If you did this
the browse would simply output the title of the variable as text.

There is a second way of outputting the values of variables, other than using
Response.Write. The earlier code could have been written:

<%@ Language=VBScript %>


<%
OutputText = "Hello World"
=OutputText
%>

In this example, the = sign is used instead of ResponseWrite.


Variable Operations

The main benefits to storing information in variables is that you can use the
text over and over again. For example, once storing "Hello World" in the
variable OutputText, I can then use it in various places in my code:

<%@ Language=VBScript %>

<% OutputText = "Hello World" %>

This is my <% =OutputText %> script. The whole reason for it is to output the
text <% =OutputText %> to the browser.

which would display in the browser:

This is my Hello World script. The whole reason for it is to output the text
Hello World to the browser.

6
Variables

A variable is a container for a value. In VBScript, all variables are variants, or


untyped variables, meaning that any sort of value-numeric, text or an object-
can be stored in a variable. This diverges from most programming
environments, which use strongly typed variables such as Integer or String.
You use the DIM statement to declare a variable. The values of text variables
are enclosed in double quotation marks. You can also concatenate string
variables with the & operator:
You can declare VBScript variables with the Dim, Public or the Private
statement. Like this:
Dim x
Dim carname

Now you have created two variables. The name of the variables are "x"
and "carname".

You can also declare variables by using its name in a script. Like this:

carname="Volvo"

<% Dim FirstName, LastName,


FullName FirstName=”Bob”LastName=”Robertson” FullName=FirstName
& ” ” & LastName Response.Write(FullName) %>

Numeric variables don’t require quotation marks:

<% Dim A,B, C A=100 B=200 C=A+B Response.Write(C) %>

The scope of a variable refers to its accessibility by the application (ASP site).
How you can access a variable depends on where you declare it in the
application:

 A procedure-level variable is declared inside a procedure and destroyed


when the procedure ends. It can only be accessed from with that
procedure.
 A local variable is declared outside a procedure and can be accessed from
anywhere on the page.

7
 A session variable is accessible by all pages in a site but applies only to a
single client (user). In ASP, sessions are created when a user enters a site
and destroyed when the user fails to access a page on a site in a specified
period of time. Session variables typically store information about that
user.
 An application variable is accessible by all pages in a site and can be used
by all clients accessing the site.
You can also do various operations on text stored in variables using len, left
and right.

The len function simply tells you how many characters are in a string, so if you
used the following code:

<% =len(OutputText) %>

The server would return to the browser the length of the text stored in
OutputText, in this case "Hello World", so the browser would display the
number 11 on the screen. You could also ssign this value to a variable using:

<% StringLength = len(OutputText) %>

which would set the value of the variable called StringLength to 11.
You can also use the functions left and right. These will display only part of the
variable. For example:

<% =left(OutputText, 2) %>

which would display:

He
and the code:

<% =right(OutputText, 4) %>

would display:

orld
Basically, these functions take the number of characters specififed from the
left or right of the string, so left("Some Text", 5) takes the first 5 characters of
the text.

Rules for VBScript variable names:

8
 Must begin with a letter
 Cannot contain a period (.)
 Cannot exceed 255 characters

In VBScript, all variables are of type variant, that can store different types of
data.

you can use the Option Explicit statement. This statement forces you to
declare all your variables with the dim, public or private statement.

Put the Option Explicit statement on the top of your script. Like this:

Option Explicit
Dim carname
carname=some value

Assigning Values to Variables

You assign a value to a variable like this:

carname="Volvo"
x=10

The variable name is on the left side of the expression and the value you want
to assign to the variable is on the right. Now the variable "carname" has the
value of "Volvo", and the variable "x" has the value of "10".

The Lifetime of Variables

 A variable declared outside a procedure can be accessed and changed by


any script in the ASP file.
 A variable declared inside a procedure is created and destroyed every
time the procedure is executed. No scripts outside the procedure can
access or change the variable.
 To declare variables accessible to more than one ASP file, declare them
as session variables or application variables.

Session Variables

Session variables are used to store information about ONE single user, and are
available to all pages in one application. Typically information stored in
session variables are name, id, and preferences.

9
Application Variables

Application variables are also available to all pages in one application.


Application variables are used to store information about ALL users in one
specific application.

ASP String Function List


Strings, or variables that take letters and numbers, are used in just about
every ASP script written. A string can be anything from "Hello, world" to "Four
score and seven years ago" to "a thousand dollars."
Here are some ASP string functions that allow you to work with your string
variables.

Asc Returns the ascii code of a given character.


cStr Converts an integer or other numeric value into a string.
InStr Located the first occurrence of a character or characters within a
string.
LCase Makes an entire string lower case.
Left Gets the leftmost X characters from a string
Len Tells you the number of characters in a string.
Mid Extracts a group of characters from the center of a string.
Replace Replaces a character or characters within a string with a new
character or characters.
Right Gets the rightmost X characters from a string
Split Break a string up into bits based on spaces, periods, or other
characters.
Trim Removes any spaces from the beginning or end of a string.
UCase Makes an entire string upper case.

VARIABLES:

For a regular variable, you simply assign a value to it. You don't have to
predefine it - it knows by what type of variable you're assigning to it what sort
of a variable it is. So if you say:
SiteName = "ASP"
it knows it's a text variable that you can do text operations on. If you say
BooksOrdered = 13
then it knows it's a numeric variable and that you can do addition and
10
subtraction to it.
The date subtype needs a special format so that the system doesn't think it's
just a string or a division problem :). You use # signs to indicate it's a date, as
in:
DateStarted = #01/15/2001#
Also, if you want to use booleans (true/false), you simply use TRUE or FALSE
as your values. So:
FinishedTask = TRUE

Constant variables

A constant is a variable whose value is not changed by the execution of the


program.

We would declare a variable to represent tax rate as a constant by the


following:

const TAXRATE = .05


Defining and Using Arrays in ASP
Arrays in ASP follow the exact same form and rules as those arrays in
VBScript. You can create an array of specific size or you can create a dynamic
sized array. Below we have examples of both types of arrays.

ASP Code:

<%
Dim myFixedArray(3) 'Fixed size array
Dim myDynArray() 'Dynamic size array
%>
We are going to focus on fixed size arrays first and cover dynamic arrays later
on in this lesson.

Assigning values to an array

Let's fill up our fixed size array with values. Our fixed array is going to store
the names of famous people. To assign a value to an array you need to know
three things:

 The name of the array


 The value you want to store
 The position in the array where you want to store the value.

11
An array is a group of variables that you can access by specifying
the positioninside the array. Our array myFixedArray has four positions: 0, 1, 2
and 3. Let's assign some values to our array.

ASP Code:

<%
Dim myFixedArray(3) 'Fixed size array
myFixedArray(0) = "Albert Einstein"
myFixedArray(1) = "Mother Teresa"
myFixedArray(2) = "Bill Gates"
myFixedArray(3) = "Martin Luther King Jr."
%>
asp arrays are zero based!

you only allocated three elements for that array, but you assigned four values!
Well, this can be done because arrays in ASP are zero based. This means when
you declare fixed array of size X then you can assign values for each value
from 0 through X.

Below is perfectly functional ASP code that will go through our array and print
out the contents of each element. Don't worry if you are confused by this
new for loop code it will be taught later.

ASP Code:

<%
Dim myFixedArray(3) 'Fixed size array
myFixedArray(0) = "Albert Einstein"
myFixedArray(1) = "Mother Teresa"
myFixedArray(2) = "Bill Gates"
myFixedArray(3) = "Martin Luther King Jr."
For Each item In myFixedArray
Response.Write(item & "<br />")
Next
%>

12
Display:

Albert Einstein Mother Teresa Bill Gates Martin Luther King Jr.

ASP dynamic sized arrays

To create an array whose size can be changed at any time simply do not put a
number within the parenthesis when you declare the array. When you know
what size you want the array to be use the ReDim keyword. You may ReDim as
many times as you wish.

If you want to keep your data that already exists in the array then use
the Preserve keyword. Below is an example of all these things we have just
talked about.

ASP Code:

<%
Dim myDynArray() 'Dynamic size array
ReDim myDynArray(1)
myDynArray(0) = "Albert Einstein"
myDynArray(1) = "Mother Teresa"
ReDim Preserve myDynArray(3)
myDynArray(2) = "Bill Gates"
myDynArray(3) = "Martin Luther King Jr."
For Each item In myDynArray
Response.Write(item & "<br />")
Next
%>
Display:

Albert Einstein Mother Teresa Bill Gates Martin Luther King Jr.

ASP: Multidimensional Arrays

Arrays do not have to be a simple list of keys and values; each location in the
array can hold another array. This way, you can create a multi-dimensional
array. The reason you may use this type of array is when you have records of

13
each item. For example, car, year, price,... and you want display one record at
a time.

The most commonly used are two-dimensional arrays. You can think of a two-
dimensional array as a matrix, or grid, with width and height or rows and
columns. Here is how you could define two-dimensional array and display the
array values on the web page:

Example:

<%@ LANGUAGE="VBSCRIPT" %>


<%
Dim arrCars(2,4)
'arrCars(col,row)
arrCars(0,0) = "BMW"
arrCars(1,0) = "2004"
arrCars(2,0) = "45.000"
arrCars(0,1) = "Mercedes"
arrCars(1,1) = "2003"
arrCars(2,1) = "57.000"
arrCars(0,2) = "Audi"
arrCars(1,2) = "2000"
arrCars(2,2) = "26.000"
arrCars(0,3) = "Bentley"
arrCars(1,3) = "2005"
arrCars(2,3) = "100.00"
arrCars(0,4) = "Mini"
arrCars(1,4) = "2004"
arrCars(2,4) = "19.00"
Response.Write(" <TABLE border=1>")
Response.Write("<TR><TD>Row</TD> <TD>Car</TD>")
Response.Write("<TD>Year</TD><TD>Price</TD></TR>")
'The UBound function will return the 'index' of the highest element in an
array.
For i = 0 to UBound(arrCars, 2)

14
Response.Write("<TR><TD>#" & i & "</TD>")
Response.Write("<TD>" & arrCars(0,i) & "</TD>")
Response.Write("<TD>" & arrCars(1,i) & "</TD>")
Response.Write("<TD>" & arrCars(2,i) & "</TD></TR>")
Next
Response.Write("</TABLE>")
%>

ASP: Functions and Subprocedures

Functions and procedures provide a way to create re-usable modules of


programming code and avoid rewriting the same block of code every time you
do the particular task. If you don't have any functions/procedures in your ASP
page, the ASP pages are executed from top to bottom, the ASP parsing engine
simply processes your entire file from the beginning to the end. ASP/VBScript
functions and procedures, however, are executed only when called, not inline
with the rest of the code. A function or subprocedure can be reused as many
times as required, thus saving you time and making for a less clustered looking
page. To declare a subroutine (a function that doesn’t return a value, starts
with the Sub keyword and ends with End Sub), you simply type:

<%@ LANGUAGE="VBSCRIPT" %>


<%
Sub subroutineName( parameter_1, ... , parameter_n )
statement_1
statement_2
...

15
statement_n
end sub
%>

A function differs from a subroutine in the fact that it returns data, start with
Function keyword and end with End Function. Functions are especially good
for doing calculations and returning a value. To declare a function, the syntax
is similar:

<%@ LANGUAGE="VBSCRIPT" %>


<%
Function functionName( parameter_1, ... , parameter_n )
statement_1
statement_2
...
statement_n
end function
%>

Have a look at the code for a procedure that is used to print out information on
the page:

<%@ LANGUAGE="VBSCRIPT" %>


<%
Sub GetInfo(name, phone, fee)
Response.write("Name: "& name &"<br>")
Response.write("Telephone: "& telephone &"<br>")
Response.write("Fee: "& fee &"<br>")
End Sub
%>

Now let's consider how to call the sub. There are two ways:

<%
'the first method
Call GetInfo("Mr. O'Donnel","555-5555",20)
'the second one
GetInfo "Mr. O'Donnel","555-5555",20 %>

16
In each example, the actual argument passed into the subprocedure is passed
in the corresponding position. Note that if you use the Call statement, the
arguments must be enclosed in parentheses. If you do not use call, the
parentheses aren't used.

Now let's look at the code for a function that takes an integer value and
returns the square of that value. Also included is code to call the function.

<%
Function Square(num)
Square = num * num
end function
'Returns 25
Response.Write(Square(5))

'Should print "45 is less than 8^2"


if 40 < Square(7) then
Response.Write("45 is less than 8^2")
else
Response.Write("8^2 is less than 40")
end if
%>

To return a value from a function, you need to name the output value the same
as your function or you will not get a value returned.

Code Comments

In the programming world, a comment is text that the compiler would not
consider when reading the code. As such a comment can be written any way you
want. In VBScript, the line that contains a comment can start with a single quote.
Here is an example:

' This line will not be considered as part of the code

Alternatively, you can start a comment with the Rem keyword. Anything on the
right side of rem, Rem, or REM would not be read. Here is an example:

Rem I can write anything I want on this line

17
Comments are very useful and you are strongly suggested to use them regularly.
They can never hurt your code and they don't increase the size of your
application. Comments can help you and other people who read your code to
figure out what a particular section of code is used for, which can be helpful
when you re-visit your code after months or years of not seeing it.

Line Continuation: _

You will regularly need to expand your code on more than one line. This
happens if you are writing an expression that involves many entities that must
belong to a group.

To continue a line of code to the next, type an empty space followed by an


underscore symbol, then continue your code on the next line.

ADO Database Connection

Before a database can be accessed from a web page, a database connection has
to be established.

Create a DSN-less Database Connection

The easiest way to connect to a database is to use a DSN-less connection. A


DSN-less connection can be used against any Microsoft Access database on
your web site.

If you have a database called "northwind.mdb" located in a web directory like


"c:/webdata/", you can connect to the database with the following ASP code:

<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
%>

Note, from the example above, that you have to specify the Microsoft Access
database driver (Provider) and the physical path to the database on your
computer.

18
Create an ODBC Database Connection

If you have an ODBC database called "northwind" you can connect to the
database with the following ASP code:

<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Open "northwind"
%>

With an ODBC connection, you can connect to any database, on any computer
in your network, as long as an ODBC connection is available.

An ODBC Connection to an MS Access Database

Here is how to create a connection to a MS Access Database:

1. Open the ODBC icon in your Control Panel.


2. Choose the System DSN tab.
3. Click on Add in the System DSN tab.
4. Select the Microsoft Access Driver. Click Finish.
5. In the next screen, click Select to locate the database.
6. Give the database a Data Source Name (DSN).
7. Click OK.

Note that this configuration has to be done on the computer where your web
site is located. If you are running Personal Web Server (PWS) or Internet
Information Server (IIS) on your own computer, the instructions above will
work, but if your web site is located on a remote server, you have to have
physical access to that server, or ask your web host to do this for you.

The ADO Connection Object

The ADO Connection object is used to create an open connection to a data


source. Through this connection, you can access and manipulate a database.

Connection Object

The ADO Connection Object is used to create an open connection to a data


source. Through this connection, you can access and manipulate a database.

19
If you want to access a database multiple times, you should establish a
connection using the Connection object. You can also make a connection to a
database by passing a connection string via a Command or Recordset object.
However, this type of connection is only good for one specific, single query.

ProgID

set objConnection=Server.CreateObject("ADODB.connection")

Properties

Property Description
Attributes Sets or returns the attributes of a Connection
object
CommandTimeout Sets or returns the number of seconds to wait
while attempting to execute a command
ConnectionString Sets or returns the details used to create a
connection to a data source
ConnectionTimeout Sets or returns the number of seconds to wait
for a connection to open
CursorLocation Sets or returns the location of the cursor
service
DefaultDatabase Sets or returns the default database name
IsolationLevel Sets or returns the isolation level
Mode Sets or returns the provider access permission
Provider Sets or returns the provider name
State Returns a value describing if the connection is
open or closed
Version Returns the ADO version number

Methods

Method Description
BeginTrans Begins a new transaction
Cancel Cancels an execution
Close Closes a connection
CommitTrans Saves any changes and ends the current

20
transaction
Execute Executes a query, statement, procedure or
provider specific text
Open Opens a connection
OpenSchema Returns schema information from the provider
about the data source
RollbackTrans Cancels any changes in the current transaction
and ends the transaction
Events

Note: You cannot handle events using VBScript or JScript (only Visual Basic,
Visual C++, and Visual J++ languages can handle events).

Event Description
BeginTransComplete Triggered after the BeginTrans
operation
CommitTransComplete Triggered after the CommitTrans
operation
ConnectComplete Triggered after a connection
starts
Disconnect Triggered after a connection
ends
ExecuteComplete Triggered after a command has
finished executing
InfoMessage Triggered if a warning occurs
during a ConnectionEvent
operation
RollbackTransComplete Triggered after the
RollbackTrans operation
WillConnect Triggered before a connection
starts
WillExecute Triggered before a command is
executed

21
Collections

Collection Description
Errors Contains all the Error objects of the Connection
object
Properties Contains all the Property objects of the Connection
object

To be able to read database data, the data must first be loaded into a
recordset.

Create an ADO Table Recordset

After an ADO Database Connection has been created, as demonstrated in the


previous chapter, it is possible to create an ADO Recordset.

Suppose we have a database named "Northwind", we can get access to the


"Customers" table inside the database with the following lines:

<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"

set rs=Server.CreateObject("ADODB.recordset")
rs.Open "Customers", conn
%>

Create an ADO SQL Recordset

We can also get access to the data in the "Customers" table using SQL:

<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs=Server.CreateObject("ADODB.recordset")
rs.Open "Select * from Customers", conn
%>

22
Extract Data from the Recordset

After a recordset is opened, we can extract data from recordset.

Suppose we have a database named "Northwind", we can get access to the


"Customers" table inside the database with the following lines:

<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"

set rs=Server.CreateObject("ADODB.recordset")
rs.Open "Select * from Customers", conn

for each x in rs.fields


response.write(x.name)
response.write(" = ")
response.write(x.value)
next
%>

The ADO Recordset Object

The ADO Recordset object is used to hold a set of records from a database
table.

Examples

GetRows
This example demonstrates how to use the GetRows method.

Recordset Object

The ADO Recordset object is used to hold a set of records from a database
table. A Recordset object consist of records and columns (fields).

In ADO, this object is the most important and the one used most often to
manipulate data from a database.

23
ProgID

set objRecordset=Server.CreateObject("ADODB.recordset")

When you first open a Recordset, the current record pointer will point to the
first record and the BOF and EOF properties are False. If there are no records,
the BOF and EOF property are True.

Recordset objects can support two types of updating:

 Immediate updating - all changes are written immediately to the


database once you call the Update method.
 Batch updating - the provider will cache multiple changes and then
send them to the database with the UpdateBatch method.

In ADO there are 4 different cursor types defined:

 Dynamic cursor - Allows you to see additions, changes, and deletions


by other users.
 Keyset cursor - Like a dynamic cursor, except that you cannot see
additions by other users, and it prevents access to records that other
users have deleted. Data changes by other users will still be visible.
 Static cursor - Provides a static copy of a recordset for you to use to
find data or generate reports. Additions, changes, or deletions by other
users will not be visible. This is the only type of cursor allowed when
you open a client-side Recordset object.
 Forward-only cursor - Allows you to only scroll forward through the
Recordset. Additions, changes, or deletions by other users will not be
visible.

The cursor type can be set by the CursorType property or by the CursorType
parameter in the Open method.

Note: Not all providers support all methods or properties of the Recordset
object.

24
Properties

Property Description

AbsolutePage Sets or returns a value that specifies the page number in


the Recordset object

AbsolutePosition Sets or returns a value that specifies the ordinal position of


the current record in the Recordset object

ActiveCommand Returns the Command object associated with the


Recordset

ActiveConnection Sets or returns a definition for a connection if the


connection is closed, or the current Connection object if
the connection is open

BOF Returns true if the current record position is before the


first record, otherwise false

Bookmark Sets or returns a bookmark. The bookmark saves the


position of the current record

CacheSize Sets or returns the number of records that can be cached

CursorLocation Sets or returns the location of the cursor service

CursorType Sets or returns the cursor type of a Recordset object

DataMember Sets or returns the name of the data member that will be
retrieved from the object referenced by the DataSource
property

DataSource Specifies an object containing data to be represented as a


Recordset object

EditMode Returns the editing status of the current record

EOF Returns true if the current record position is after the last

25
record, otherwise false

Filter Sets or returns a filter for the data in a Recordset object

Index Sets or returns the name of the current index for a


Recordset object

LockType Sets or returns a value that specifies the type of locking


when editing a record in a Recordset

MarshalOptions Sets or returns a value that specifies which records are to


be returned to the server

MaxRecords Sets or returns the maximum number of records to return


to a Recordset object from a query

PageCount Returns the number of pages with data in a Recordset


object

PageSize Sets or returns the maximum number of records allowed


on a single page of a Recordset object

RecordCount Returns the number of records in a Recordset object

Sort Sets or returns the field names in the Recordset to sort on

Source Sets a string value or a Command object reference, or


returns a String value that indicates the data source of the
Recordset object

State Returns a value that describes if the Recordset object is


open, closed, connecting, executing or retrieving data

Status Returns the status of the current record with regard to


batch updates or other bulk operations

StayInSync Sets or returns whether the reference to the child records


will change when the parent record position changes

26
Methods

Method Description

AddNew Creates a new record

Cancel Cancels an execution

CancelBatch Cancels a batch update

Cancels changes made to a record of a Recordset


CancelUpdate
object

Clone Creates a duplicate of an existing Recordset


Close Closes a Recordset
CompareBookmarks Compares two bookmarks
Delete Deletes a record or a group of records
Find Searches for a record in a Recordset that satisfies a
specified criteria
GetRows Copies multiple records from a Recordset object
into a two-dimensional array
GetString Returns a Recordset as a string
Move Moves the record pointer in a Recordset object
MoveFirst Moves the record pointer to the first record
MoveLast Moves the record pointer to the last record
MoveNext Moves the record pointer to the next record
MovePrevious Moves the record pointer to the previous record
NextRecordset Clears the current Recordset object and returns the
next Recordset object by looping through a series of
commands
Open Opens a database element that gives you access to
records in a table, the results of a query, or to a
saved Recordset
Requery Updates the data in a Recordset by re-executing the
query that made the original Recordset

27
Resync Refreshes the data in the current Recordset from
the original database
Save Saves a Recordset object to a file or a Stream object
Seek Searches the index of a Recordset to find a record
that matches the specified values
Supports Returns a boolean value that defines whether or not
a Recordset object supports a specific type of
functionality
Update Saves all changes made to a single record in a
Recordset object
UpdateBatch Saves all changes in a Recordset to the database.
Used when working in batch update mode

Events

Note: You cannot handle events using VBScript or JScript (only Visual Basic,
Visual C++, and Visual J++ languages can handle events).

Description

EndOfRecordset Triggered when you try to move to a record after


the last record

FetchComplete Triggered after all records in an asynchronous


operation have been fetched

FetchProgress Triggered periodically in an asynchronous


operation, to state how many more records that
have been fetched

FieldChangeComplete Triggered after the value of a Field object change

MoveComplete Triggered after the current position in the


Recordset has changed

RecordChangeComplete Triggered after a record has changed

28
RecordsetChangeComplete Triggered after the Recordset has changed

WillChangeField Triggered before the value of a Field object


change

WillChangeRecord Triggered before a record change

WillChangeRecordset Triggered before a Recordset change

WillMove Triggered before the current position in the


Recordset changes

Collections

Collection Description

Fields Indicates the number of Field objects in the Recordset


object

Properties Contains all the Property objects in the Recordset


object

The Fields Collection's Properties

Property Description

Count Returns the number of items in the fields


collection. Starts at zero.

Example:

countfields=rs.Fields.Count
Item(named_item/number) Returns a specified item in the fields collection.

Example:

itemfields=rs.Fields.Item(1)
or
itemfields=rs.Fields.Item("Name")

29
The Properties Collection's Properties

Property Description

Count Returns the number of items in the properties


collection. Starts at zero.

Example:

countprop=rs.Properties.Count
Item(named_item/number) Returns a specified item in the properties
collection.

Example:

itemprop = rs.Properties.Item(1)
or
itemprop=rs.Properties.Item("Name")

ADO Display

The most common way to display data from a recordset, is to display the data
in an HTML table.

Display the Field Names and Field Values

We have a database named "Northwind" and we want to display the data from
the "Customers" table (remember to save the file with an .asp extension):

Example

<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"

set rs = Server.CreateObject("ADODB.recordset")
rs.Open "SELECT * FROM Customers", conn

do until rs.EOF
for each x in rs.Fields
Response.Write(x.name)
Response.Write(" = ")
Response.Write(x.value & "<br>")

30
next
Response.Write("<br>")
rs.MoveNext
loop

rs.close
conn.close
%>
</body>
</html>

Display the Field Names and Field Values in an HTML Table

We can also display the data from the "Customers" table inside an HTML table
with the following lines (remember to save the file with an .asp extension):

Example

<html>
<body>

<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"

set rs = Server.CreateObject("ADODB.recordset")
rs.Open "SELECT Companyname, Contactname FROM Customers", conn
%>

<table border="1" width="100%">


<%do until rs.EOF%>
<tr>
<%for each x in rs.Fields%>
<td><%Response.Write(x.value)%></td>
<%nextz
rs.MoveNext%>
</tr>
<%loop
rs.close
conn.close
%>
</table>

</body>
</html>

31
Add Headers to the HTML Table

We want to add headers to the HTML table to make it more readable

Example

<html>
<body>

<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"

set rs = Server.CreateObject("ADODB.recordset")
sql="SELECT Companyname, Contactname FROM Customers"
rs.Open sql, conn
%>

<table border="1" width="100%">


<tr>
<%for each x in rs.Fields
response.write("<th>" & x.name & "</th>")
next%>
</tr>
<%do until rs.EOF%>
<tr>
<%for each x in rs.Fields%>
<td><%Response.Write(x.value)%></td>
<%next
rs.MoveNext%>
</tr>
<%loop
rs.close
conn.close
%>
</table>

</body>
</html>

32
ADO Queries

Display Selected Data

We want to display only the records from the "Customers" table that have a
"Companyname" that starts with an A (remember to save the file with an .asp
extension):

<html> <body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs=Server.CreateObject("ADODB.recordset")
sql="SELECT Companyname, Contactname FROM Customers
WHERE CompanyName LIKE 'A%'"
rs.Open sql, conn
%>
<table border="1" width="100%">
<tr>
<%for each x in rs.Fields
response.write("<th>" & x.name & "</th>")
next%>
</tr>
<%do until rs.EOF%>
<tr>
<%for each x in rs.Fields%>
<td><%Response.Write(x.value)%></td>
<%next
rs.MoveNext%>
</tr>
<%loop
rs.close
conn.close%>
</table>
</body>
</html>
33
Let the user choose filter
Let the user choose which country to show customers from.

<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/northwind.mdb"))

set rs=Server.CreateObject("ADODB.recordset")
sql="SELECT DISTINCT Country FROM Customers ORDER BY Country"
rs.Open sql,conn

country=request.form("country")

%>

<form method="post">
Choose Country <select name="country">
<% do until rs.EOF
response.write("<option")
if rs.fields("country")=country then
response.write(" selected")
end if
response.write(">")
response.write(rs.fields("Country"))
rs.MoveNext
loop
rs.Close
set rs=Nothing %>
</select>
<input type="submit" value="Show customers">
</form>

34
<%
if country<>"" then
sql="SELECT Companyname,Contactname,Country FROM Customers
WHERE country='" & country & "'"
set rs=Server.CreateObject("ADODB.Recordset")
rs.Open sql,conn
%>
<table width="100%" cellspacing="0" cellpadding="2" border="1">
<tr>
<th>Companyname</th>
<th>Contactname</th>
<th>Country</th>
</tr>
<%
do until rs.EOF
response.write("<tr>")
response.write("<td>" & rs.fields("companyname") & "</td>")
response.write("<td>" & rs.fields("contactname") & "</td>")
response.write("<td>" & rs.fields("country") & "</td>")
response.write("</tr>")
rs.MoveNext
loop
rs.close
conn.Close
set rs=Nothing
set conn=Nothing%>
</table>
<% end if %>
</body>
</html>

35
ADO Sort

We want to display the "Companyname" and "Contactname" fields from the


"Customers" table, ordered by "Companyname" (remember to save the file
with an .asp extension):

Example

<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"

set rs = Server.CreateObject("ADODB.recordset")
sql="SELECT Companyname, Contactname FROM
Customers ORDER BY CompanyName"
rs.Open sql, conn
%>

<table border="1" width="100%">


<tr>
<%for each x in rs.Fields
response.write("<th>" & x.name & "</th>")
next%>
</tr>
<%do until rs.EOF%>
<tr>
<%for each x in rs.Fields%>
<td><%Response.Write(x.value)%></td>
<%next
rs.MoveNext%>
</tr>
<%loop
rs.close
conn.close%>
</table>

</body>
</html>

36
ADO Add Records

We may use the SQL INSERT INTO command to add a record to a table in a
database.

Add a Record to a Table in a Database

We want to add a new record to the Customers table in the Northwind


database. We first create a form that contains the fields we want to collect
data from:

<html>
<body>

<form method="post" action="demo_add.asp">


<table>
<tr>
<td>CustomerID:</td>
<td><input name="custid"></td>
</tr><tr>
<td>Company Name:</td>
<td><input name="compname"></td>
</tr><tr>
<td>Contact Name:</td>
<td><input name="contname"></td>
</tr><tr>
<td>Address:</td>
<td><input name="address"></td>
</tr><tr>
<td>City:</td>
<td><input name="city"></td>
</tr><tr>
<td>Postal Code:</td>
<td><input name="postcode"></td>
</tr><tr>
<td>Country:</td>
<td><input name="country"></td>
</tr>
</table>
<br><br>
<input type="submit" value="Add New">
<input type="reset" value="Cancel">
</form>

</body>
</html>

37
When the user presses the submit button the form is sent to a file called
"demo_add.asp". The "demo_add.asp" file contains the code that will add a
new record to the Customers table:

<html>
<body>

<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"

sql="INSERT INTO customers (customerID,companyname,"


sql=sql & "contactname,address,city,postalcode,country)"
sql=sql & " VALUES "
sql=sql & "('" & Request.Form("custid") & "',"
sql=sql & "'" & Request.Form("compname") & "',"
sql=sql & "'" & Request.Form("contname") & "',"
sql=sql & "'" & Request.Form("address") & "',"
sql=sql & "'" & Request.Form("city") & "',"
sql=sql & "'" & Request.Form("postcode") & "',"
sql=sql & "'" & Request.Form("country") & "')"

on error resume next


conn.Execute sql,recaffected
if err<>0 then
Response.Write("No update permissions!")
else
Response.Write("<h3>" & recaffected & " record added</h3>")
end if
conn.close
%>

</body>
</html>
Important

If you use the SQL INSERT command be aware of the following:

 If the table contains a primary key, make sure to append a unique, non-
Null value to the primary key field (if not, the provider may not append
the record, or an error occurs)
 If the table contains an AutoNumber field, do not include this field in the
SQL INSERT command (the value of this field will be taken care of
automatically by the provider)

38
ADO Update Records

We may use the SQL UPDATE command to update a record in a table in a


database.

Update a Record in a Table

We want to update a record in the Customers table in the Northwind


database. We first create a table that lists all records in the Customers table:

<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM customers",conn
%>

<h2>List Database</h2>
<table border="1" width="100%">
<tr>
<%
for each x in rs.Fields
response.write("<th>" & ucase(x.name) & "</th>")
next
%>
</tr>
<% do until rs.EOF %>
<tr>
<form method="post" action="demo_update.asp">
<%
for each x in rs.Fields
if lcase(x.name)="customerid" then%>
<td>
<input type="submit" name="customerID" value="<%=x.value%>">
</td>
<%else%>
<td><%Response.Write(x.value)%></td>
<%end if
next
%>
</form>
<%rs.MoveNext%>
</tr>
<%
loop
conn.close
%>
39
</table>

</body>
</html>

If the user clicks on the button in the "customerID" column he or she will be
taken to a new file called "demo_update.asp". The "demo_update.asp" file
contains the source code on how to create input fields based on the fields from
one record in the database table. It also contains a "Update record" button
that will save your changes:

<html>
<body>
<h2>Update Record</h2>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"

cid=Request.Form("customerID")

if Request.form("companyname")="" then
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM customers WHERE customerID='" & cid & "'",conn
%>
<form method="post" action="demo_update.asp">
<table>
<%for each x in rs.Fields%>
<tr>
<td><%=x.name%></td>
<td><input name="<%=x.name%>" value="<%=x.value%>"></td>
<%next%>
</tr>
</table>
<br><br>
<input type="submit" value="Update record">
</form>

40
<%
else
sql="UPDATE customers SET "
sql=sql & "companyname='" & Request.Form("companyname") & "',"
sql=sql & "contactname='" & Request.Form("contactname") & "',"
sql=sql & "address='" & Request.Form("address") & "',"
sql=sql & "city='" & Request.Form("city") & "',"
sql=sql & "postalcode='" & Request.Form("postalcode") & "',"
sql=sql & "country='" & Request.Form("country") & "'"
sql=sql & " WHERE customerID='" & cid & "'"
on error resume next
conn.Execute sql
if err<>0 then
response.write("No update permissions!")
else
response.write("Record " & cid & " was updated!")
end if
end if
conn.close
%> </body> </html>

We want to delete a record in the Customers table in the Northwind database.


We first create a table that lists all records in the Customers table:

<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM customers",conn
%>

<h2>List Database</h2>

41
<table border="1" width="100%">
<tr>
<%
for each x in rs.Fields
response.write("<th>" & ucase(x.name) & "</th>")
next
%>
</tr>
<% do until rs.EOF %>
<tr>
<form method="post" action="demo_delete.asp">
<%
for each x in rs.Fields
if x.name="customerID" then%>
<td>
<input type="submit" name="customerID" value="<%=x.value%>">
</td>
<%else%>
<td><%Response.Write(x.value)%></td>
<%end if
next
%>
</form>
<%rs.MoveNext%>
</tr>
<%
loop
conn.close
%>
</table>

</body>
</html>

42
ADO Delete Records

If the user clicks on the button in the "customerID" column he or she will be
taken to a new file called "demo_delete.asp". The "demo_delete.asp" file
contains the source code on how to create input fields based on the fields from
one record in the database table. It also contains a "Delete record" button that
will delete the current record:

<html>
<body>
<h2>Delete Record</h2>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"

cid=Request.Form("customerID")

if Request.form("companyname")="" then
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM customers WHERE customerID='" & cid & "'",conn
%>
<form method="post" action="demo_delete.asp">
<table>
<%for each x in rs.Fields%>
<tr>
<td><%=x.name%></td>
<td><input name="<%=x.name%>" value="<%=x.value%>"></td>
<%next%>
</tr>
</table>
<br><br>
<input type="submit" value="Delete record">
</form>
<%
else

43
sql="DELETE FROM customers"
sql=sql & " WHERE customerID='" & cid & "'"
on error resume next
conn.Execute sql
if err<>0 then
response.write("No update permissions!")
else
response.write("Record " & cid & " was deleted!")
end if
end if
conn.close
%>
</body>
</html>

ADO Demonstration

Read this First

If you try to update the database, you will get the error message: "You do not
have permission to update this database". You get this error because you don't
have write access to our server.

BUT, if you copy the code and run it on your own system, you might get the
same error. That is because the system might see you as an anonymous
internet user when you access the file via your browser. In that case, you have
to change the access-rights to get access to the file.

How to change the access-rights of your Access database?

Open Windows Explorer, find the .mdb file. Right-click on the .mdb file and
select Properties. Go to the Security tab and set the access-rights here.

44

You might also like