Sunteți pe pagina 1din 36

Chapter 10

Active Data Objects


Essentials
Early, there were variety of objects to access database , including
Data Access Objects(DAO), designed for the Microsoft Access
database, and Remote Data Objects(RDO), designed for
enterprise databases like Oracle and SQL Server.
Active Data Objects is a key component of Microsofts universal
Data Access strategy
The idea is to give programmers a single set of Objects that can
be used in any Microsoft environment and any platform
ADO is a programming interface to access data in any database
Four major components of UDA strategy:
OLEDB
ODBC
Remote Data Service
ADO



Microsofts Universal Data Access Strategy
OLE DB is a technology designed by Microsoft to make it easier
to access all types of data through a single set of interfaces
On a Web server, you may want
To access data that Microsoft Index Server has produced
from your website. Index Server is designed to make
searchable indexes of your web data.
To access information in plain text or in other known
document types, such as Microsoft Word, or Adobe Acrobat
To do some data mining using Online Analytical
Processing(OLAP) tools
All of these sources of data are now accessible through OLE DB

OLE DB
OLE DB uses a driver called a provider
A provider know how a particular type of data is arranged,
regardless of type of data
The Provider translates the given request into a request it can
process against its particular type of data
The Programmers only has to worry about submitting a request
that resembles standard SQL language, and the provider takes
care of the rest
The application submits a request to the provider, which then
translate the request to the data source so that the data can be
sent to the application
Open Database Connectivity (ODBC) is a specification for a
database API
The API is an independent standard supported by a variety of
vendors, including Oracle, Informix, Sybase, and Microsoft
While OLE DB is able to talk directly to several different types
of database, some database do not yet have OLE DB providers
available
In these cases, you can use the ODBC driver for the database in
combination with OLE DB provider for ODBC
Using this method creates an extra layer of interface between
your code and the database (ADO->OLEDB->ODBC->database)
This will help to upgrade the application or the database at
some point

ODBC
RDS enables applications to access OLE DB providers running
on remote machines or in separate processes on the same
machine
This feature makes it easier to create dynamic web pages
Instead of bringing down all the possible data a page could use,
you get data as you need it
Limitation
The only downside to this technology is the requirement that
only Microsoft Internet Explorer will work with RDS


Remote Data Service (RDS)
Active Data Objects(ADO)
Provides a no. of objects used to traverse all types of data.
ADO defines 7 objects and 4 collections.
Objects: Connection, Command, RecordSet, Parameter, Field,
Property, Error
Collections: Fields, Parameters, Properties, Errors

The common way to access a database from inside an ASP
page is to:
Create an ADO connection to a database
Open the database connection
Create an ADO recordset
Open the recordset
Extract the data you need from the recordset
Close the recordset
Close the connection

Connection Object
A Connection Object represents a Single session with a data
source
Used to create an open connection to a data source.
Through this connection, access and manipulate a database.
ADO has multiple connection object, with each pointing to
different data sources.
Making a connection:
Dim dcnDB As ADODB.Connection
dcnDB variable to hold connection object
Set dcnDB =Server.CreateObject(ADODB.Connection)


Accessing Access 97 database:
dcnDB.ConnectionString=&Provider=Microsoft.Jet.OLEDB.3.5
1;&DataSource=C:\VisualStudio\VB98\Biblio.mdb
dcnDB.Open
Provider parameter specifies the OLEDB provider to use. (Jet
3.51 Access 97)
DataSource specify the path name to database.
Open activates connection to database.
Note: For Access 2000, change 3.51 to 4.0
Accessing SQL Server 6.5 database:
dcnDB.ConnectionString=
& Provider=SQLOLEDB.1;
& User ID=myuser; Password=mypassword; & Initial
Catalog=PUBS;
& Data Source=db.server.com
dcnDB.Open
SQL Server requires user ID and password.

<%@ language="JavaScript" %>
<html>
<body>
<%
var myConnect = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=";
myConnect += "d:/sample.mdb";
(OR)
myConnect += Server.MapPath(sample.mdb"); //database in server
var conn=Server.CreateObject("ADODB.Connection")
conn.Open(myConnect)
Response.Write("Database working")
%>
</body>
</html>
Data Link File
Microsoft provides a way to specify database connection
information.
Used to specify all same information about database
connection as in previous.
Kept outside the ASP page, which makes secure, especially if it
located in a directory that not accessible by web
If you have any part of visual studio 6.0 installed , you can
follow these steps to create a Data Link File
Start Windows Explorer
Navigate to the directory where to create Data Link File.
Select File -> New -> Microsoft Data Link, Enter name of
the Data Link File and press Enter.
Right click the file and select open from pop-up menu.
Default data link is created using ODBC OLEDB provider.
(Access Jet Provider in Provider tab)
After selecting the Provider click Next.
In Connection tab, select database to use and click Test
Connection button to verify Data link is set up correctly.
Specify full path name of data link file.
Advantage is that if the database location or connection
method changes, make a single change to a Data Link File and
all of the connections will be changed



Dim dcnDB As ADODB.Connection
Set dcnDB =Server.CreateObject(ADODB.Connection)
dcnDB.ConnectionString=File Name=C:/sample.udl
dcnDB.Open
Another way of creating Data Link File

ADO supports storing Connection information in an external file called a
Data Link File (which normally has a *.UDL extension)

The process of creating a new Data Link File is simple and straightforward:

1. Right Click in Windows Explorer and choose New ==> Text Document.
Doing so will create a New Text Document (*.TXT) in the current Folder.
2. Rename the file to any name you like, changing the extension to .UDL.
Windows will warn you that changing the file name extension may
make the file unusable; respond Yes to this warning.
3. Double-Click the file to edit the Data Link properties.
4. Select the Provider tab and choose the appropriate Provider.
5. Select the Connection Tab and fill in the Database Name and Log in
information.
6. Click the Test Connection button to verify that the information entered
is correct, and then click OK to save the file.

<%@ language = "javascript" %>
<html>
<body>
<%
var conn = Server.CreateObject("ADODB.Connection")
connStr = "File Name=d:/sample.udl;"
conn.Open(connStr)
Response.Write("Connection Success")
conn.close
%>
</body>
</html>
Closing a Connection
When end of the ASP page, always close any open data
connections.
Enables data source server to release system resources
associated with that connection.
dcnDB.Close
Before closing, ensure any other objects using it.
Clear object references using,
Set dcnDB=Nothing
RecordSet
To read database data, the data must first be loaded into a
recordset.
It is a set of records.
Suppose database named sample", we can get access to the
student" table inside the database with the following lines:



var RS = Server.CreateObject("ADODB.Recordset");

var sql="SELECT * FROM student";
RS.Open(sql,conn);

(OR)

RS.Open("SELECT * FROM student",conn);

var no=101;
var sql="SELECT * FROM student WHERE regno="+no+";";

var n1="Sam";
var sql="SELECT sname,regno FROM student WHERE
sname="+"'"+n1+"'"+";";



RS.Open("Select * from student",conn,
adOpenForwardOnly,adLockReadOnly,adCmdText);

Cursor type: adOpenForwardOnly, adOpenKeyset,
adOpenDynamic, adOpenStatic (0-3)

Method by which the records should be locked:
adLockReadOnly, adLockPessimistic, adLock Optimistic,
adLockBatchOptimistic (1-4)

High traffic environment pessimistic lock
Low traffic environment optimistic lock

<!-- METADATA TYPE="typelib" FILE="C:\Program Files\Common
Files\System\ado\msado15.dll" -->

Navigating Recordset
Display or process the records through loop.
while (!RS.EOF)
{
Response.Write( "<br>"+RS("sname")+ " and " +
RS("regno") );
RS.MoveNext();
}
rs.Close
MoveFirst, MoveLast, MoveNext, MovePrevious
Executing a Query
Execute the query against the database

var sql="SELECT COUNT(*) FROM bank;";
var rs=Server.CreateObject("ADODB.Recordset");
rs=conn.Execute(sql);
Response.Write("No of Records in Database "+rs(0));

Execute method run SQL commands entered directly into ASP
code.
Execute all types of query inserts, updates and deletes.

conn.Execute("Insert into bank (accname, accno) values ('sss',
119)");
conn.Execute("UPDATE bank SET accname = 'John' where
accno=119");
conn.Execute("DELETE from bank WHERE accno=119;");


Doesnt return recordsets.

Also execute stored procedures and predefined queries.
Also pass string to procedure
SELECT * FROM bank WHERE accno=1;

var RS=Server.CreateObject("ADODB.Recordset");
RS=conn.Execute('spReterival');

SELECT * FROM bank WHERE accname=@ID;

var RS=Server.CreateObject("ADODB.Recordset");
RS=conn.Execute("spReterival1 'Anu'");

Editing Recordsets
var RS = Server.CreateObject("ADODB.Recordset");
var no=1;
var sql="SELECT accno, accname FROM bank WHERE accno=1;";
RS.Open(sql,conn,adOpenKeySet,adLockOptimistic,adCmdText);
Response.Write("Record Found");
RS("accno")=225;
RS.Update();
Response.Write("Update Finished");
Adding new records
var RS = Server.CreateObject("ADODB.Recordset");
var sql="SELECT accno, accname FROM bank;";
RS.Open(sql,conn,adOpenKeySet,adLockOptimistic,adCmdText);
Response.Write(RS("accno"));
RS.AddNew();
RS("accno")=108;
RS("accname")="ccc";
RS.Update();
Response.Write("Record Added");
Deleting Records
var RS = Server.CreateObject("ADODB.Recordset");
var sql="SELECT accno, accname FROM bank WHERE
accno=108;";
RS.Open(sql,conn,adOpenKeySet,adLockOptimistic,adCmdText);
Response.Write(RS("accno"));
RS.Delete
Response.Write("Record Deleted");
Command Object
Used to execute a single query against a database.
The query can perform actions like creating, adding,
retrieving, deleting or updating records.
If the query is used to retrieve data, the data will be returned
as a RecordSet object.
The major feature of the Command object is the ability to use
stored queries and procedures with parameters.

var cmdQ=Server.CreateObject("ADODB.Command");
cmdQ.CommandText="SELECT * FROM bank;";
cmdQ.ActiveConnection=conn;

var RS=Server.CreateObject("ADODB.Recordset");
RS=cmdQ.Execute();
while(!RS.EOF)
{
Response.Write(RS("accno")+" "+RS("accname")+"<br>")
RS.MoveNext
}
RS.Close();
Before all these statement create a ADODB Connection and
connection string
CommandText holds text of query
ActiveConnection holds active database connection
Execute runs query & create resulting recordset object
Running query with parameter
Piece of information given to stored procedure or query called
parameter.
Parameters have name, type, direction and size.

spReterival1
SELECT * FROM bank WHERE accname=[@ID];
spReterival2
SELECT * FROM bank WHERE accno=[@ID];
var cmdQ=Server.CreateObject("ADODB.Command");
cmdQ.CommandText='spReterival1';
cmdQ.ActiveConnection=conn;

var parID=Server.CreateObject("ADODB.Parameter");
parID=cmdQ.CreateParameter("accname",adVarChar,adParamIn
put,20,'Anu');

cmdQ.Parameters.Append(parID);

var RS=Server.CreateObject("ADODB.Recordset");
RS=cmdQ.Execute();

var cmdQ=Server.CreateObject("ADODB.Command");
cmdQ.CommandText='spReterival2';
cmdQ.ActiveConnection=conn;

var parID=Server.CreateObject("ADODB.Parameter");
parID=cmdQ.CreateParameter("accno",adInteger,adParamInput,
0,2);
cmdQ.Parameters.Append(parID);

var RS=Server.CreateObject("ADODB.Recordset");
RS=cmdQ.Execute();
Errors Collection
Holds all database errors that occur when you run your
application
Dim dcnDB
Dim cmdQuery
Dim rsQuery
Dim parID
Dim intLoop
On Error Resume Next
Set dcnDB = Server.CreateObject("ADODB.Connection")
dcnDB.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data
Source=d:/sample.mdb"
dcnDB.Open
Response.Write("Database working"+"<br>")
Set cmdQuery=Server.CreateObject("ADODB.Command")
cmdQuery.CommandText = "SELECT * FROM baank"
Set cmdQuery.ActiveConnection = dcnDB
If dcnDB.Errors.Count > 0 then
For intLoop = 0 to dcnDB.Errors.Count-1
Response.Write dcnDB.Errors(intLoop).Description
Response.Write dcnDB.Errors(intLoop).Source
Next
Else
Set rsQuery = cmdQuery.Execute
Do While Not rsQuery.EOF
Response.Write rsQuery("accname")
rsQuery.MoveNext
Loop
rsQuery.Close
End If
dcnDB.Close

S-ar putea să vă placă și