Professional Documents
Culture Documents
Unit 4
Unit 4
CONNECTTION OBJECT
*the connection object is directly related to thee command and record set objects
<%
MySQL =”delete from student”
Set con= server .create object (“ADODB Connection”)
Con,open “FILE NAME =C;\my datalink UDL “
Con.execute mySQL
%>
*the above scripts remove all the rows from the student table however it does not remover the
table itself
5 SELECTING DATA FROM THE DATABASE TABLE:
*to retrive rows from a database table use the SQL select statement
* for example to retirve all the rows from the student table use the following scipt
<%
MySQL –‘select ‘from student “
Set con= server createobject (AD0DB connection “)
Con .open “FILE NAME =C;\my datalink.UDL”
Set RS = con.execute (My SQL)
Whilw not RS EOF
Response .write RS(“username “)& “=”RS(“password “)&”<br>”
RS move next
WEND
%>
*the above script retrieves all the columns and the rows from the table named student into a
record set object named RS next all the rows from the recordset are send as output to the
browser within a WHILE…..WEND loop
ADVANCED METHODS AND PROPERTIES OF THE CONNECTION OBJECT:
1.USING TRANSACTION
*A transaction is a series of SQL Statement placed one below the other. To maintain integrity
of the transaction all SQL Statement must succeed together or none of the SQL statement
must succeed. If the transaction fails all changes done to the database table/s must be rolled
back.
*The connection object can be used to guarantee the integrity of a transaction.
*For example,suppose there is a script that moves all the rows from one table to another , we
use the following script
<%
Set con =server.createobject(“^DODB.Connection”)
Con.open”FILE NAME=c:\myDataLink.UDL”
Con.execute”insert into WebUsers2select*from WebUsers”
Con.execute”Delete WebUsers”
%>
The above script is executed, First it copies all the rows from the table named
WebUsers2. Next, all the rows from the WebUsers table are deleted
UNDERSTANDING SESSIONS AND CONNECTION POOLING:
*OLEDB Supports sessions pooling.
*Sessions are special environments that the Web server creates for each user of an
application.
*Sessions variables are variables that are used by the user who is logged on the application
during that session.
CONNECTION POOLING
*Connection pooling is enabled by default when using either the OLE DB provider for SQL
Server or the OLE DB provider for ODBC drivers.
*When the connections are pooled, database connection remain open,even after the Active
Server Page that requested the connections has finished processing. When a new connection
is requested, the connection can be drawn from the pool. The time consuming step of opening
a new connection is avoided.
*The following must be kept in mind to get the most out of the connection pooling
STEP 1
After opening the consuming within the Active Server Page, close the connection
as soon as possible to release the connection back to the connection , pool. Until a
connection is closed , it cannot be reused . Use the close method of Connection
object too close the connection after finishing with it.
STEP 2
Connections can be pooled only when they share the same Connection string.For
example, if a connection is opened with a new value for the UID parameter, then
the new connection cannot be pooled with connection that uses a different value
for the UID parameter.
STEP 3
To ensure that different Active Server Pages are using the same connection string
to open connections, assign the connection string to an ‘Application variable’.
Example:Application(“conString”)=”FILE NAME = c:\myDataLink.UDL”
STEP 4
Finally, always be aware that connection pooling can cause a lot of problems
when using connection-specific properties of the SQL Server.
WORKING WITH RECORD SETS
1.Recording a recordset
* if a SQL statement that returns rows froms a database table is executed, the rows are
returned wuth an ADO Recordset Object.
* A Recordset object can be used to represent the rows or it can be used to represent dozens
or even millions of rows.
*Examples : FileName:SHOWTABLE .ASP
<html>
<head>
<body>
<title>Show Table </title>
</head>
<body
<%
Set con = server.createobject(“ADODB.connection”)
Con.open”FILE NAME = c:\myDataLink.UDL;DATA BASE = Authors ist”
Ste rs = con.execute(“select*from Authors ORDER BY au_Iname”)
%>
<table border=1>
<%while not rs.eof%>
<tr>
<td> <%=rs(“au_Iname”) %> </td>
<td> <%=rs(“au_fname”) %> </td>
<td> <%=rs(“au_phone”) %> </td>
</tr>
<%
rs.movenext
wend
rs.close
%>
</table>
</body>
</html>
2 RECORDSET FIELDS
*every recordset contains a fields collection the fields collection contains indivuals fields
objects the field in the fileds collection represent the columns returnrd frpm the database
query the fields collection can be used in a number or different ways to display a column
value
*the value of an individual field can be displayed by using the name of the field for example
the following scripts dispalys a columns named phone by name
<%
Set.con=server.createobject(“ADODB/connection”)
Con.open “filename =c:\my datalink.UDL:DATABASE=authorlist”
Set rs =con.execute (“select phone from authors where au_inames=’kalam’)
Response .write rs (“phone”)
%>
*the above script retrives a single column and row from the authoroized database table an
display the column’s value it retrives the phone number of the author who has the last name
kalam and display it
PROPERTIES OF FIELD OBJECT :
*the field object has serval other useful properties that can be used in ASP scripts to retrive
information about the columns returned ny quering a table
1.ACTUALSIZE
* it is used with columns that return the actual lengrh of the data stored in the column
2.ATTRIBUTES
* it includes several different properties of a column for example this propery can be used to
determine whether a column can contain null values or whether the column has a variable or
fixed length data type
3 DEFINED SIZE :
*the maximum number of bytes (or charcters)that a column can contain for example a
VARCHAR column may have a define size 500 but a actualsize of 2
4 name
*it specifies the name of a column
5.NumericScale
* it returns the scale of the column ( the maximum number of digits that can be appear to the
right of the decimal point )
6. OriginalValue
*when the field id updateable, this column contains the original value of the field in the
Recordset before it was changed
7. precision
* it returns the precisions of the column ( the maximum number of digits that can appear to
the left and right of the decimal point )
8.Type
* it containsthe data type of a column. For example, whether the column is a Date or
VACHAR column.
9.UnderlyingValue
*it contains the current value of the column in the database table.
10. Value
* it specifies the value of the column
* this property is never used explicitly because it is the default property of the field object.
RECORDSET CURSOR AND LOCKING TYPES :
* whenever a recordset is opened either implicity or explicity a cursor is created in memory
which will have a behaviour called LOCKING assocsisted with it
*understanding cursor and locking types is important for serval reasons they are
1 first using different cursor and locking types can have a dramstic effect on the performance
of asp scipts if wrong chocies are made it can take forever for the ASP scripts to retrives and
display a list of database records
2 second certain properties of the recordset object are available only when the correct cursor
and its associated locking behaviour type is used for example a record set must be opened
with the right cursor and locktype to retrives a count of tie records in recordset of to hold a
recordset that contain update able records
UNDERSTANDING ADD CURSORS :
*when you execute an SQL statement the result is sent back in the form to rows to add using
cursors
* a cursor is a pointer or set of pointer to data extracted from a database that meets specified
criteria cursors allow you to work with sets of data
* cursors are generally a represenatation of real data and can have any of the following
attributes
ATTRIBUTES OF CURSORS
*they can be represent some or all nrecords in a single table
* they can be represent some or all records in a multiple table join
* they can represent no records
*they can be read only or updateable at either the cursor or the field level
*they can be fully scoolable (meaning that you can more forward and backward through thre
records) or they can be forward obackwards through the records)
*they can exits or either the client or the server
To divide a recordset into pages, use the pageSize property to set the number of
records in a page. Next,after opening the recordset, use the absolutepage property
to move to a particular page. The following examples shows how the records in
the table named title car be displayed using multiple pages
PAGING.ASP
<!--#INCLUDE FILE = “adovbs.inc”-- >
<html>
<head>
<title>Paging Through a Recordset</title>
</head>
<body>
<%
Dim current,I,rowcount
Currentpage = trim(request (“currentpage”))
If currentpage = “”then currentpage = 1
Set con = server. Createobject (“ADODB.connection”)
Con.open”provider = Microsoft.jet.o edb.4.0;data source
=“&server.mappath(“stud.mdb”)
Set rs = server.createobject (“ADODB.recordset”)
Rs.cursortype = adopenstatic
Ra.pagesize = 2
Rs. Open “select*from student”,con
Rs.absolute = currentpage
Rowcount = 0
While not rs.eof and rowcount <rs.pagesize
Response.write rs(“rlno”)&”<br>”
For i=0 to rs.pagecount
%>
<a href = “paging.asp?currentpage=<%=i%>”><%=i%><a/>
<% next %>
</body>
</html>
Two considerations needed for choosing the correct cursor and locking type for a
Recordset are:
The need for performance
The need for particular reocrdset properties.
FIREHOSE MODE:
When the default cursor (forward-only cursor)is used with SQL server, the cursor
is opened in firehose mode.
It is called firehose mode because the connection is kept open and the results of
the query are blasted to the application as fast as possible.
EXAMPLE FOR ABSOLUTEPOSITION PROPERTY:
<!--#include VIRTUAL=”/adovbs.inc”-- >
<%
Set con = server.createobject(“ADODB.connection”)
Con.open “FILENAME=c:\myDataLink.UDL;DATABASE=pubs”
Set rs = server.createobject(“ADODB.recordset”)
Rs.cursortype = adopenstatic
Rs.open”select * from authors ORDER BY au_Iname”,con
Rs.absoluteposition = rs.recordcount/2
Response.write rs (“au_Iname”)
%>
The above script retrieves and display the record that appears in the middle of the
recordset
The “absoluteposition”enable the users to move directly to any record according
to it position.
BOOKMARK PROPERTY:
The bookmark property can be used to return a unique identifier for a record
The following script creates a bookmark for a record,and then repositions the
recordset cursor to the bookmark
<!--#include VIRTUAL = “/adovbs.inc”-- >
<%
Set con = server.createobject(“ADODB.connection”)
Con.open “FILENAME=c:\myDataLink.UDL;DATABASE=pubs”
Set rs = server.createobject(“ADODB.recordset”)
Rs.cursortype = adopenstatic
Rs. Open “select*from authors ORDER BY au_Iname”,con
While not rs.EOF
If rs(“au_Iname”)=”Locksley”then
Set the bookmark
Mybookmark=rs.bookmark
End if
Rs.movenext
Wend
Return to the bookmark
Response.write rs (“au_Iname”)
%>
In this example, a bookmark is created when a record containing the value
locksley is found.
After the end of the recordset has been reached, the recordset pointer is
repositioned to this record by using the bookmark.
ADOVBS.INC:
The adovbs.inc file is a text file that contains a long list of constants used with an
ADO
This file was installed an a server when internet information server was installed.
The adovbs.inc file can be found in the Inetpub \iisamples\Issamples directory on
the web server.
Limiting the number of records returned in a recordset:
It is necessary that all records are not retrieved from a table . for example, when
only the first 15 records from table or the top 10 percent of the records from a
table need to be retrieved.
There are two ways that can limit the number of records returned in a database
query:
*by using the ADO maxrecords property
*by using the SQL server TOP keyword.
The following script uses the “maxrecords” property of the recordset object to
retrieved no more than 15 authors from the authors table:
<%
Set con = server.createobject (“ADODB.connection”)
Con.open”FILENAME=c:\myDataLink.UDL;DATABASE=pubs”
Set rs = server.createobect(“ADODB.recordset”)
Rs.maxrecordset=15
Rs.open “select*from authors ORDER BY au_Iname,”con while not rs.EOF
Response.write rs (“au_Iname”)&”<br>”
Rs.movenext
Wend
%>
This script retrieves the first 15 authors in order of their last names.
The following script uses the top keyword to return the top 15 records:
<%
Set con=server. Createobject (“ADODB.connection”)
Con.open “FILENAME=C:\myDataLink.UDL;DATABASE=pubs”
Set Rs=Server. Createobject(“ADODB.Recordset”)
RS.open “SELECT top 15 * FROM Authors ORDER BY au_Iname”,con while not rs.EOF
Response.write rs (“au_Iname”)&”<br>”
Rs.movenext
Wend
%>
The “TOP” keyword can also be used to return a certain percentage of records
from a database table.
The following script retrieves the top 15 percent of records from the authors table
by using the “PERCENT” keyword
<%
Set con = server.createobject(“ADODB.connection”)
Con.open “FILENAME = c:\myDataLink.UDL;DATABASE = pubs”
Set rs = server.createobject(“ADODB.recordset”)
Rs.open “SELECT TOP 15 PERCENT * FROM Authors while not rs.EOF
ORDER BY au_Iname”,con
Response.write rs(“au_Iname”)&”<br>”
Rs.movenext
Wend
%>
UPDATING RECORDS WITH NATIVE ADO METHODS:
Instead of using SQL statement to alter records, native ADO methods can be used.
The use of ADO methods for updating records should be avoided because they are
less efficient than SQL commands.
ADO METHODS:
1. Add new: adds a new record
2. Cancel update: cancels any changes made to a record. It must be used before the
update method is called or before moving to a new record.
3. Delete: deletes the current record
4. Resync: used with a forward-only or static cursor to resynchorinze a recordset with
the umderlying database table after changes have been made.
ADO PROPERTIES:
1.Editmode:* this property returns the current editing state
*IT can have the values
2.original value: when a field is updateable , this column contaims the original value
of the field in the Rcordset before it was changed.
3.UNDERLYING VALUE: contains the current value of the column in the database
table the value of this property can differ from the “originalvalu “property because the
column in recordst was retrieved.
This script saves the authors recordset to a file with the name “myfile.rst”.
The recordset is saved using the ADTG format.
ADDNEW:
To add a new record to a database table,the”addnew” method can be used.
Eg: <! - - #INCLUDE VIRTUAL = “/adovbs.inc”- - >
<%
Set con = server.createobject(“ADODB.connection”)
Con.open”FILENAME” = c:\myDataLink.UDL;DATABASE = pubs”
Set rs = server.createobject(“ADODB.recordset”)
Rs.locktype = adlockoptimistic
Rs.open”SELECT*FROM webusers WHERE 1< > 1”,con
Rs.Addnew
Rs(“username”) = “Andrew jones”
Rs(“password”) = “won’t say”
Rs.update
%>
This script adds a new record to a database table named webusers.
It adds a user with the name “Andrew Jones” and the password “won’t say”.
The table is opened with a SQL query that returns no records.
The query request every record where 1< >1, because it is metaphysically
impossible for 1 to be not equal to itself, no records are returned.
NOTES:
When a SQL string that contains an apostrophe with the “connection” object is
execute, an error is generated.
SQL uses the apostrophe character to mark the beginning and end of the string
value.
No error is generated when apostrophe are used with the native ADO methods for
updating recordsets
DELETE:
To delete a record, the ADO”Delete” method can be used.
Eg: <! - - # INCLUDE VIRTUAL = “/adovbs.inc” - - >
<%
Set con = server.createobject(“ADODB.connection”)
Con.open “FILENAME = c:\myDataLink.UDL;DATABASE = pubs”
Set rs = server.createobject(“ADODB.Recordset”)
Rs.locktype = adlockoptimistic
Rs.open “SELECT * FROM webusers WHERE username=”Andrew Jones”,con
Rs.Delete
Rs.Update
%>
This script retrieves a recordset that contains all the records from the “ webusers”
table where the username is “Andrew Jones”.
Next,the ADO Delete method is called to delete the current record.
When the “Delete” method is called, only the current record is deleted.
If the recordset contains hundreds of record where the username id “Andrew
Jones”,only one record would be removed – the first Andrew Jones record.
UPDATE:
To update a recordset, simply a new value can be assigned to a field.
The following script changes the password for “Andrew Jones” to the value “very
secret”:
< ! - - #INCLUDE VIRTUAL = “/adovbs.inc” - - >
<%
Set con = server.createobject(“ADODB.connection”)
Con.open”FILENAME=c:\myDataLink.UDL;DATABASE = pubs”
Set rs = server.createobject(“ADODB.recordset”)
Rs.locktype = adlockoptimistic
Rs.open”SELECT*FROM webusers WHERE username = “Andrew Jones”,con
Rs(“password”) = “very secret”
Rs.update
%>
To load the recordset from the file, a file path can be used, a relative file path, or
even a URL.
The following script loads the recordset by using a filepath and displays all its
records:
<%
Set con = server.createobject(“ADODB.connection”)
Rs.open “c:\myfile.rst”
While not rs.EOF
Response.write rs (“au_Iname”)&”<br>”
Rs.movenext
Wend
%>
If the recordset file is saved in a web directory, a URL can be used to load the file.
The following script loads the same recordset from a URL:
<%
Set con = server.createobject(“ADODB.connection”)
Rs.open http://www.somewhere.com/myfile.rst
While not rs.EOF
Response.write rs (“au_Iname”)&”<br>”
Rs. Movenext
Wend
%>
Persistent recordset provides to easily distriout data from a database table.
Persistent recordset can be used to pass data between web servers or between a
webserver and a client application that uses an ADO
----------------------------XXXXXXXXXXXX---------------------------------------------