Docstoc

Oracle is one of the most popular databases in the world_ also

Document Sample
Oracle is one of the most popular databases in the world_ also Powered By Docstoc
					Oracle is one of the most popular databases in the world, also Active Server Pages (ASP) is a powerful
server-side scripting language widely used to build dynamic Web pages. There are many ASP
developers who wonder if they can use the ASP technology with Oracle database to build a web
application, E-commerce and E-business web sites or internet management systems. The answer is YES!
You can access Oracle using VB to create Oracle Applications as well. Here, I will discuss with you how to
use ASP dealing with Oracle data.

       Before we start, there are a few things you need to know. The Oracle Objects for OLE (OO4O)
method is one of them. The OO4O is an Oracle middleware that allows native access to Oracle from
client applications using the Microsoft Object Linking and Embedding (OLE) standard. Some of you may
think that the ODBC can be used. Surely, you can use the standard database access method developed by
Microsoft Corporation to access Oracle, but in my opinion the OO4O is better than ODBC because the
OO4O is thread safe and provides full support for PL/SQL. PL/SQL stands for Procedural Language/SQL. It
is an Oracle extension of the SQL statement set which allows the developer to impose flow control and
logic design onto unstructured SQL command blocks. If you have fully installed Oracle8i, I am sure the
OO4O is there for use already. If not, you can download it from Oracle web site.

    The other thing is, we need know two objects and one interface that Oracle developed for Visual Basic
Development, OraSession and OraDynaset objects, and OraDatabase interface. The OraSession
object manages collections of OraDatabase, OraConnection, and OraDynaset used within an application.
It is the object created by the CreateObject ASP and not by an OO4O method. The OraDatabase
interface represents a user session to an Oracle database and provides methods for SQL and PL/SQL
execution. Each of them has some of properties, and methods. For instance, the OraDynaset has some of
properties, such as BOF, EOF, Bookmark, Connection, and so on, and ten methods, such as AddNew,
Update, Delete, Edit, Refresh, Clone, and so on.

   Now, let's start working on Oracle data using ASP technology.


Preparation
   What do you need?

   1) Development and running environments I am using are Oracle8i, IIS5.0, Windows2000
Professional.

   2) Build a table into the Oracle database, and called "MYTABLE1" something like this.


ID
                                                 Phone(type:
(type:           User Name(type: varchar2)                                Email(type: varchar2)
                                                 varchar2)
number)
100              Colin Tong                      999-999-8888             colinjava@hotmail.com
111              John White                      888-888-8888             johnw@yahoo.com
101              Don Wod                         416-333-3344             donwod@test.com



Access and retrieve data
   1) Instantiate OO4O Object, OraSession and interface OraDatabase for connecting to ORACLE.
   First of all, create the OraSession Object by using CreateObject, then create the OraDatabase Object
by opening a connection to Oracle, as shown below.



<%
Set OraSession = CreateObject("OracleInProcServer.XOraSession")
Set OraDatabase = OraSession.OpenDatabase("", _
     "username/password", Cint(0))
%>

   The "username" and "password" are your relational database's user name and password.
   2) Create an OraDynaset Object to execute SQL statement. You may use either CreateDynaset or
DbCreateDynaset to create the recordset.



<%
'execute SQL
Set OraDynaset = OraDatabase.DbCreateDynaset( _
    "select * from mytable1", cint(0))
%>

     3) Retrieve data and remove created object

<%
     Do While(OraDynaset.EOF = FALSE)
       Response.write(OraDynaset.Fields("ID"))
       Response.write(OraDynaset.Fields("UserName"))
       ... others ...
       ... ...
       OraDynaset.MoveNext
     Loop
     'remove OraSession
     Set OraSession = Nothing
%>



Edit data record
  We are going to use the methods of OraDynaset to implement the editing data purpose.

     1) Create OraDynaset object with SQL Statement



<%
'Create the OraDynaset Object for ID= fID record.
Set OraDynaset = OraDatabase.CreateDynaset(_
    "select * from MYTABLE1 where ID= "& fID, cint(0))
%>


     The fID is the value of the ID field that you want to update or insert.



  2) Execute OraDynaset for updating or adding



<%
       'update the field of the record(ID=fID) using Edit method.
       'or use the AddNew to insert a new record
       OraDynaset.Edit
       OraDynaset.Fields("Phone").Value = fPhone
       OraDynaset.Update

       ' remove the created session
       Set OraSession = Nothing
%>
Delete data record
   Some of you might already know how to delete record(s) from Oracle DB using OraDynaset if you
really understand the methods that we used (Edit, Update and AddNew) at above sections. Actually,
we simply use the method Delete of OraDynaset for deleting.



<%
     'Delete all records that with above condition.
     OraDynaset.Delete
%>



Sample codes for search and update data records from
Oracle8i
  1) Searching



<%
 '*************************************************************
 'RetrieveRecProc.asp -Retrieve records using OO4O in ASP
 'Original Author: Colin Tong
 'Modified Date: 9/26/2001
 'Note: You are free to use this code, however, please keep
 'the original author name.
 '*************************************************************
%>
<%
'Declare variables as OLE Objects.
 Dim OraSession
 Dim OraDatabase
 Dim OraDynaset


'Create the OraSession Object.
 Set OraSession = CreateObject("OracleInProcServer.XOraSession")

'Create the OraDatabase Object by opening a connection to Oracle.
'Be sure your own username and password to access your Oracle db
 Set OraDatabase = OraSession.OpenDatabase("", "user/password", _
     Cint(0))

'Create the OraDynaset Object to execute SQL statement
 Set OraDynaset = OraDatabase.DbCreateDynaset(_
     "select * from mytable1", cint(0))
%>
<html><body>
<H3>Retrieve All Records in MYTABLE1 Table ( in Oracle)
    Using oo4o</H3>
<table border=1 ID="Table1">
<%
 Do While(OraDynaset.EOF = FALSE)
   Response.Write("<tr><td>")
   Response.write(OraDynaset.Fields("ID"))
   Response.Write("</td><td>")
   Response.write(OraDynaset.Fields("UserName"))
   Response.Write("</td><td>")
   Response.write(OraDynaset.Fields("Phone"))
   Response.Write("</td><td>")
   Response.write(OraDynaset.Fields("Email"))
   Response.Write("</td></tr>")
   OraDynaset.MoveNext
 Loop

 'remove OraSession
 Set OraSession = Nothing
%>
</table>
<a href="javascript:window.history.go(-1)">
Back previous Page</a> |
<a href="index.html"> Back home Page</a>
</body></html>


 2) Updating



<%
'**************************************************************
'UpdateRecProc.asp -Update a record using OO4O in ASP
'Original Author: Colin Tong 'Modified Date: 9/26/2001
'Note: You are free to use this code, however please keep
'the original author name.
'**************************************************************
%>
<%
'Declare variables as OLE Objects. Dim OraSession
 Dim OraDatabase
 Dim OraDynaset

 'get field values from submitted form
 fID = request.form("ID")
 fUserName = request.form("UserName")
 fPhone = request.form("Phone")
 fEmail = request.form("Email")

 'Create the OraSession Object
 Set OraSession = CreateObject("OracleInProcServer.XOraSession")

 'Create the OraDatabase Object by opening a connection to Oracle
 Set OraDatabase = OraSession.OpenDatabase("", "user/password", _
     Cint(0))

 'Create the OraDynaset Object for ID= fID record
 Set OraDynaset = OraDatabase.CreateDynaset(_
     "select * from MYTABLE1 where ID= "& fID, cint(0))

'update the field of the record(ID=fID) using Edit method
 Do While(OraDynaset.EOF = FALSE)
    OraDynaset.Edit
    OraDynaset.Fields("UserName").Value = fUserName
     OraDynaset.Fields("Phone").Value = fPhone
     OraDynaset.Fields("Email").Value = fEmail
     OraDynaset.Update
     OraDynaset.MoveNext
 Loop
%>
<html><body>
<H3>Update A Record in MYTABLE1 Table (Oracle) Using oo4o</H3>
The record (ID=<%=fID%>) has been updated successfully!<br>
You can view the result <a href="RetrieveAllRec.asp"> here</a>
<p>
<a href="javascript:window.history.go(-1)"> Back previous Page</a>
&bnsp;&bnsp;
<a href="javascript:window.history.go(-2)"> Back home Page</a>
<%
    'remove OraSession
     Set OraSession = Nothing
%>
</body></html>


  Now, you should know how to use OO4O to deal with Oracle database in your ASP code.


Use Stored Procedures
   So far we have discussed how ASP pages access Oracle database, and all SQL statements
are embedded in ASP pages. As most of you know, if the stored procedures have been used, it will
definitely make extracting data more efficient. I strongly recommend you use PL/SQL Stored Procedures in
the Database except embedding sql in ASP code. Creating Stored Procedures in Oracle is beyond this
topic, however, I would like to introduce it next time, if number of visitors are interested in it. Email me if
you are interested in.

   Because of time and the limit of my own knowledge, some errors might be found on this article, you
are welcome to comment. Feel free to use any of the codes in this article, however, do so at your own
risk.


<%@ Language=VBScript %> <html> <head> <title>Oracle Test</title>
</head> <body> <center> <% Set objConn =
Server.CreateObject("ADODB.Connection") objConn.Open
"Provider=MSDAORA;Data Source=<Your_TNSNames_Alias>;User
Id=<userid>;Password=<password>;" Set objRs = objConn.Execute("SELECT *
FROM DEMO.EMPLOYEE") Response.Write "<table border=1 cellpadding=4>"
Response.Write "<tr>" For I = 0 To objRS.Fields.Count - 1
Response.Write "<td><b>" & objRS(I).Name & "</b></td>" Next
Response.Write "</tr>" Do While Not objRS.EOF Response.Write "<tr>" For
I = 0 To objRS.Fields.Count - 1 Response.Write "<td>" & objRS(I) &
"</td>" Next Response.Write "</tr>" objRS.MoveNext Loop Response.Write
"</table>" objRs.Close objConn.Close %> </center> </body> </html>
 Introduction
Active Server Pages (ASP) is a server-side scripting language widely used to build dynamic Web pages.
The ASP Engine processes the script on the Web server at the back end and sends only HTML to any
browser. Since the script is processed at the server, the requesting browser will be catered, even if it does
not support a scripting language.

Oracle is one of the most used relational databases. Oracle Objects for OLE (OO4O) is an Oracle
middleware that allows native access to Oracle from client applications using the Microsoft Object Linking
and Embedding (OLE) standard. But performance-wise it is better than Open DataBase Connectivity
(ODBC), a standard database access method developed by Microsoft Corporation, to access Oracle. OO4O
is thread safe and provides full support for PL/SQL. Connection pooling is also available with later
versions of OO4O.

This article describes practical Oracle Database connectivity from ASP using OO4O. It also explains the
execution of pass through SQL, and Procedure and Package from ASP, which are commonly used in data-
driven dynamic Web applications.

Installation of OO4O

OO4O can be freely downloaded from Oracle’s site. The creation of an oo4o directory by the installer
under Oracle home confirms the successful installation. OO4O also works well with Oracle 7.0 or later.

All the examples are based on a fictitious Products table, which comprises the below-mentioned structure.

Table Products

             Field Name                    Data Type
PID                                        NUMBER
PNAME<TDVARCHAR2< TD>



Including an oo4oglobals.asp file in a project is a good practice. All oo4o constants are defined in this file
(see below):


&lt;%
Const OK = 0
Const ERROR = 32767

const    ORATYPE_VARCHAR2=1
const    ORATYPE_NUMBER=2
const    ORATYPE_SINT=3
const    ORATYPE_FLOAT=4
const    ORATYPE_STRING=5
const    ORATYPE_VARCHAR=9
const    ORATYPE_DATE=12
const    ORATYPE_UINT=68
const    ORATYPE_CHAR=96
const    ORATYPE_CHARZ=97

const ORAPARM_INPUT=1
const ORAPARM_OUTPUT=2
const ORAPARM_BOTH=3
%&gt;


Execution of Pass through SQL Using OO4O

The following ASP code demonstrates the execution of pass through SQL using OO4O. Step 1: Making
the Connection


&lt;%
Dim OraSession
Dim OraDatabase
Dim osRecordSet
Set OraSession = Server.CreateObject("OracleInProcServer.XOraSession")
Set OraDatabase = OraSession.DbOpenDatabase("", "scott/tiger",cint(0))
%&gt;

OLE Server - OraSession object is instantiated by the CreateObject method. DbOpenDatabase method of
OraSession is used to open a connection. The DbOpenDatabaseMethod takes database name, username,
password, and a mode parameter as inputs. The mode parameter cint(0) specifies the result return format
(default or Visual Basic mode). This mode will set null values to columns that are not explicitly specified
during AddNew and Edit methods of the oo4o object.

Step 2: Executing SQL


&lt;%
Set osRecordSet = OraDatabase.DbCreateDynaset("select pid, pname from
PRODUCTS", cint(0))
%&gt;

DbCreateDynaset method of OraDatabase creates a Dynaset from the specified SQL statements. The
parameter cint(0) specifies the mode as discussed in the connection open method.

Step 3: Retrieving Results


&lt;TABLE BORDER=1&gt;
&lt;TR&gt;
&lt;TD WIDTH=30&gt;
&lt;B&gt;PID&lt;/B&gt;
&lt;/TD&gt;
&lt;TD WIDTH=200&gt;
&lt;B&gt;Product Name&lt;/B&gt;
&lt;/TD&gt;
&lt;/TR&gt;
&lt;%
Do While(osRecordset.EOF = FALSE)
%&gt;
        &lt;TR&gt;
        &lt;TD WIDTH=30&gt;
&lt;%
        Response.write(osRecordset.Fields("PID"))
%&gt;
           &lt;/TD&gt;
           &lt;TD WIDTH=200&gt;
&lt;%
           Response.write(osRecordset.Fields("PNAME"))
%&gt;
           &lt;/TD&gt;

        &lt;/TR&gt;
&lt;%
osRecordSet.MoveNext
Loop
%&gt;
&lt;/TABLE&gt;

A Dynaset created by the oo4o object will always point to an initial record of a database connection. The
server script will manipulate the Dynaset result set to present the results to the browser. Movenext is an
often-used method to navigate through Dynasets.

Step 4: Closing the Connection


&lt;%Set OraSession = Nothing%&gt;

Closing the connection frees up all the system resources being used.

Execution of Oracle Procedure Using OO4O

The following ASP code demonstrates the execution of a stored procedure within a database using OO4O.

Step 1: Making the Connection


&lt;!--#INCLUDE FILE="oo4oglobals.asp"--&gt;
&lt;%
Dim OraSession
Dim OraDatabase
Dim osRecordSet
Dim nResult

nPID=10
sPNAME="HDD"

Set OraSession = Server.CreateObject("OracleInProcServer.XOraSession")
Set OraDatabase = OraSession.DbOpenDatabase("", "scott/tiger",cint(0))
%&gt;

Note: For demo purposes, the input values to the procedure are hard-coded.

Step 2: Executing Procedure


&lt;%
OraDatabase.Parameters.Add "nPID", nPID, ORAPARM_INPUT
OraDatabase.Parameters ("nPID").ServerType = ORATYPE_NUMBER

OraDatabase.Parameters.Add "sPNAME",sPNAME, ORAPARM_INPUT
OraDatabase.Parameters ("sPName").ServerType = ORATYPE_VARCHAR2

nResult=OraDatabase.DbExecuteSql("begin SP_INS_PRODUCT(:nPID,:sPNAME);
end; ")
%&gt;

In the example above, the Add method adds parameters to the collection. Name, value, and I/O type are
taken as input. I/O type constants are defined in oo4oglobals.asp. DbExecuteSql executes the formatted
PL/SQL statements and returns the number of rows processed.

Step 3: Retrieving Results
If there are any output parameters for a procedure, they can be retrieved after the procedure execution.

Step 4: Closing the Connection


&lt;%
OraDatabase.Parameters.Remove "nPID"
OraDatabase.Parameters.Remove "sPNAME"
Set OraSession=Nothing
%&gt;

Re-initializing the parameters to specific needs can promote the reuse of objects. Therefore, purely program
logic, and not the resource availability, will influence the decision on closing or keeping a database session.

Procedure Used for Demo:


/******************************************************
Procedure:     SP_INS_PRODUCT
Desc     :     Insert a product
Author    :    Selva Kumar
******************************************************/
CREATE OR REPLACE PROCEDURE SP_INS_PRODUCT(nPID IN NUMBER, sPNAME IN
VARCHAR2)
AS BEGIN
INSERT INTO PRODUCTS(PID,PNAME) VALUES(nPID,sPNAME);
END;


Execution of Oracle Package Using OO4O

The following ASP code demonstrates the execution package using OO4O.

Step 1: Making the Connection


&lt;!--#INCLUDE FILE="oo4oglobals.asp"--&gt;
&lt;%
Dim OraSession
Dim OraDatabase
Dim osRecordSet

 Set OraSession = Server.CreateObject("OracleInProcServer.XOraSession")
 Set OraDatabase = OraSession.DbOpenDatabase("", "scott/tiger",cint(0))
%&gt;


Step 2: Executing Package


&lt;%
Set osRecordset = _
OraDatabase.CreatePLSQLDynaset _
("Begin RET_PRODUCTS.SP_RET_PRODUCTS(:iProducts); end;", _
"iProducts",cint(0))
%&gt;

CreatePLSQLDynaset creates a Dynaset from PL/SQL cursor. This method takes SQL Statements, a cursor
created by stored procedure, and a mode parameter as input.

Step 3: Retrieving Results


&lt;%
Do While(osRecordset.EOF = FALSE)
%&gt;
        &lt;TR&gt;
        &lt;TD WIDTH=30&gt;
&lt;%
        Response.write(osRecordset.Fields("PID"))
%&gt;
        &lt;/TD&gt;
        &lt;TD WIDTH=200&gt;
&lt;%
        Response.write(osRecordset.Fields("PNAME"))
%&gt;
        &lt;/TD&gt;

        &lt;/TR&gt;
&lt;%
osRecordSet.MoveNext
Loop
%&gt;
&lt;/TABLE&gt;


Step 4: Closing the Connection


&lt;%Set OraSession = Nothing%&gt;


Package Used for Demo:
Package Definition:
/******************************************************
Package : RET_PRODUCTS
Procedure:      SP_RET_PRODUCTS
Desc     :      Returning all products
Author   :      Selva Kumar
******************************************************/

CREATE OR REPLACE PACKAGE RET_PRODUCTS
AS
CURSOR C1 IS SELECT * FROM PRODUCTS;

TYPE tProducts is ref cursor return C1%rowtype;

PROCEDURE SP_RET_PRODUCTS
(iProducts in out tProducts);
END RET_PRODUCTS;
/

Package Body:
/******************************************************
Package :      RET_PRODUCTS
Procedure:     SP_RET_PRODUCTS
Desc     :     Returing all products
Author   :     Selva Kumar
******************************************************/

CREATE OR REPLACE PACKAGE BODY RET_PRODUCTS
AS
PROCEDURE SP_RET_PRODUCTS
(iProducts in out tProducts)
IS
BEGIN
        OPEN iProducts for Select * from PRODUCTS;
end SP_RET_PRODUCTS;
END;
/



Topics
           What is ASP and what is it used for?
           What is the difference between ASP and JSP?
           What Web Servers can be used for hosting ASP pages?
           How does one configure ASP servers for Oracle?
           How does one connect to Oracle from an ASP page?
           How does one call stored procedures from an ASP page?
           Where can one get more info about ASP?

Back to Oracle FAQ Index



What is ASP and what is it used for?
Active(X) Server Pages (ASP) is a language-independent framework designed by Microsoft to
generate dynamic web content. It allows coding of server-side scripts that are executed by a Web
server in response to a user's request for a URL. ASP scripts are similar to other server-side
scripting technologies like Java Server Pages, Perl Server Pages and so on.

An ASP page is a standard ASCII text file that contains both HTML tags and scripting code.
Typical scripting languages that can be embedded into ASP pages are VBScript and JavaScript.
All scripting portions are delimited by <% and %> tags. Example ASP page:

            <html>

            Current date and time is:

            <%

               ' Start comments with "'"
               response.write "<B>"

               response.write Now() ' writes the current date and time.

            %>

            </html>

 Back to top of file



What is the difference between ASP and JSP?
Active Server Pages (ASP) is a Microsoft standard, which is easier to develop than Java Server
Pages (JSP). ASP supports multiple scripting languages (VBScript, JavaScript, etc), but is limited
to Microsoft supported platforms and software.

JSP supports customizable tags and is independent of platform and server technologies. Code is
developed using the standard Java programming language. Either ODBC or JDBC is used to
connect to Oracle (and other) databases. JSP is usually used for larger enterprise scale
applications. For more information about JSP Pages, see the JDBC FAQ.

 Back to top of file



What Web Servers can be used for hosting ASP pages?
Active Server Pages are supported on the following Web Servers:

        Microsoft Personal Web Server (PWS)
        Microsoft Internet Information Services (IIS)
        Some Unix Web Servers

 Back to top of file



How does one configure ASP servers for Oracle?
Follow these steps to ensure your server can connect to Oracle:

    1.   Make sure that you can use simple ASP pages. Upload (FTP) the example above to your server
         and see if you can access it via a Web Browser.
    2.   Install the Oracle Client CD on your server. This will install SQL*Net, OO4O (Oracle Objects for
         OLE) and the Oracle ODBC drivers on your system.
    3.   Configure SQL*Net and ensure you can tnsping and connect your Oracle database. This is done by
         adding an entry to the TNSNAMES.ORA file or by using utilities like the "Net Easy Configurator" to
         do it for you. See the SQL*Net FAQ for details.
    4.   Optionally configure ODBC by creating a System DSN (Data Source Name). This can be done from
         the "32-Bit ODBC Administrator" in the Control Pannel. Alternatively one can use OO4O (no
         configuration required), or "DSNless" ODBC connection. See the ODBC FAQ for details.
    5.   You are ready to GO!!!

 Back to top of file



How does one connect to Oracle from an ASP page?
One can connect to Oracle from ASP Pages using the Oracle ODBC driver or OO4O (Oracle
Objects for OLE) calls. Look at this OO4O example:

            <%

            Set OraSession =
 Server.CreateObject("OracleInProcServer.XOraSession")

            Set OraDatabase = OraSession.DbOpenDatabase("connect_str.world",
 "hr/hr",cint(0))



                 Response.Write "OO4O Version:            " & OraSession.OIPVersionNumber &
 "<BR>" & _

                                   "Username:             " & OraDatabase.connect                    &
 "<BR>" & _

                                   "Database Name:        " & OraDatabase.DatabaseName               &
 "<BR>" & _

                                   "Oracle Version: " & OraDatabase.RDBMSVersion                     &
 "<BR>"



            Set osRecordSet = OraDatabase.DbCreateDynaset("SELECT TNAME FROM
 TAB", cint(0))

                 Response.write("<H1>Tables:</H1>")



                 Do While(osRecordset.EOF = FALSE)

                    Response.write(osRecordset.Fields("TNAME") & "<BR>")

                    osRecordSet.MoveNext

                 Loop
         %>

The following example domonstrated ODBC connectivity:

         <%
           Set OraDatabase = Server.CreateObject("ADODB.Connection")

           OraDatabase.Open "dsn=OracleDSN;uid=userid;pwd=password;"

           Set osRecordSet = OraDatabase.Execute("SELECT * FROM EMPLOYEE")

           Response.Write "<table border=1 cellpadding=4>"

           Response.Write "<tr>"



           For I = 0 To osRecordSet.Fields.Count - 1

                Response.Write "<td><b>" & osRecordSet(I).Name & "</b></td>"

           Next



           Response.Write "</tr>"



           Do While Not osRecordSet.EOF

               Response.Write "<tr>"

               For I = 0 To osRecordSet.Fields.Count - 1
                   Response.Write "<td>" & osRecordSet(I) & "</td>"

               Next

               Response.Write "</tr>"

               osRecordSet.MoveNext

           Loop



           Response.Write "</table>"



           osRecordSet.Close

           OraDatabase.Close

         %>

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:15
posted:3/8/2010
language:English
pages:14