Chapter 9 Server-Side

This chapter is a detailed reference of all the items and elements making up the server-side JavaScript language. This refers to the implementation available in the Netscape and iPlanet Web Server Enterprise Edition, which we will simply refer to as Enterprise Server (ES) from this point on, and within Microsoft's Active Server Pages (ASP) environment, which is available for their Internet Information Server (IIS) or Personal Web Server (PWS).

Because both Microsoft and Netscape have taken different approaches for their server-side implementation, be sure to check the supported environments for these entries. Additionally, be sure to read Chapter 5, "JavaScript on the Server-Side," for more information on how these implementations are used.

As in other chapters of Part III, the details of the language are covered in this chapter. Each entry includes the language version, syntax, description, and an example of each server-side–specific language element.

The chapter is in alphabetical order, by JavaScript objects, to provide you with quick, easy access to the methods, properties, functions, and event handlers of every server-side object. These appear alphabetically after the respective parent object using simple dot notation.

addClient()

ES2+

 

Syntax

addClient(URL)

Description

The addClient() function is a top-level function that is not associated with any core object. This function is used to preserve the property values of a client object when you generate dynamic links or use the redirect() function. The addClient() function takes a URL as its only parameter.

Example

This example demonstrates how you can use the addClient() function when dynamically building links. In Listing 9.1, a link is built by using a property of the project object.

Listing 9.1 Using the addClient() Function to Dynamically Build a Link

<a href='<server>addClient("/myApp/page" +
project.pagenum + ".html")</server>'>
Please proceed to the next page</a>

In Listing 9.2, the addClient() function is used in conjunction with the redirect() function. This will send the user to the URL specified in the addClient() function.

Listing 9.2 Using the addClient() Function with the redirect() Function

<server>
// Check to see if the browser is Internet Explorer.
if(request.agent.indexOf('MSIE') != -1){
   redirect(addClient("/iepages/index.html"));
// Redirect to another page if it is not IE.
}else{
   redirect(addClient("/defaultpages/index.html"));
}
</server>

addResponseHeader()

ES3+

 

Syntax

addResponseHeader(keyvalue)

Description

The addResponseHeader() function is a top-level function that is not associated with any core object. This function is used to add fields and values to the HTTP header sent back to the client. Because of when the actual header is sent in relation to the body of the data, you should be sure to set these fields and values before you call the flush() or redirect() functions.

Example

Listing 9.3 shows how you can send back a dynamically built external JavaScript source file to a browser with the proper content-type header field and value.

Listing 9.3 Using the addResponseHeader() Function to Set the content-type of a File Being Sent to a Browser

<server>

// Add a field to the header
addResponseHeader("content-type", "application/x-javascript");
</server>

Application

ASP1+

 

Syntax

Core ASP environment object

Description

The Application object is a core ASP environment object. It is used to share information across all users of a given application, which includes all .asp files as well as any virtual directories and their subdirectories. Table 9.1 contains the methods, collections, and events of this object.

Table 9.1 Methods, Collections, and Events of the Application Object

Image

Example

Listing 9.4 shows how you could specify the version of your application that users are implementing, and then write it out.

Listing 9.4 Using the Application Object

<script runat="server" type="text/jscript" language="JScript">
Application("version") = "1.0"
var appVer = Application("version");
Response.Write(appVer);
</script>

Application.Application_OnEnd

ASP1+

 

Syntax

function Application_OnEnd(){
  code
}

Description

The Application_OnEnd event function of the Application object is called when the Application_OnEnd event is fired. This occurs when the application quits, which is after the Session_OnEnd event is fired.

Example

Listing 9.5 shows how you can append a string to the end of the log file of the last request of an application.

Listing 9.5 Using the Application_OnEnd Event

<script runat="server" type="text/jscript" language="JScript">
function Application_OnEnd(){
 Response.AppendToLog("Your application has ended");
}
</script>

Application.Application_OnStart

ASP1+

 

Syntax

function Application_OnStart(){
code
}

Description

The Application_OnStart event function of the Application object is called when the Application_OnStart event is fired. This occurs when the application starts, which is before the Session_OnStart event is fired.

Example

In Listing 9.6 shows how you can append a string to the end of the log file on the first request of an application.

Listing 9.6 Using the Application_OnStart Event

<script runat="server" type="text/jscript" language="JScript">
function Application_OnStart(){
   Response.AppendToLog("Your application has started");
}
</script>

Application.Contents

ASP1+

 

Syntax

Application.Contents(name)

Description

The Contents collection of the Application object contains all the items that have been added to the application through script commands. You are able to access a specific item by specifying its name.

Example

Listing 9.7 shows how you can use the Remove() method of the Contents collection to remove myItem, which was added to the application.

Listing 9.7 Using the Contents Collection

<script runat="server" type="text/jscript" language="JScript">
// Add the item to the collection.
Application("myItem") = "My name is Allen";
// Remove the item.
Application.Contents.Remove("myItem");
</script>

Application.Contents.Remove()

ASP1+

 

Syntax

Application.Contents.Remove(name)
Application.Contents.Remove(num)

Description

The Remove() method of the Contents collection of the Application object is used to remove an item from the application's collection. This item can either be referenced by its name or its num index position.

Example

Listing 9.8 shows how you can use the Remove() method of the Contents collection to remove myItem, which was added to the application.

Listing 9.8 Using the Remove() Method

<script runat="server" type="text/jscript" language="JScript">
// Add the item to the collection.
Application("myItem") = "My name is Allen";
// Remove the item.
Application.Contents.Remove("myItem");
</script>

Application.Contents.RemoveAll()

ASP1+

 

Syntax

Application.Contents.RemoveAll()

Description

The RemoveAll() method of the Contents collection of the Application object is used to remove all items from the application’s collection.

Example

Listing 9.9 shows how you can use the RemoveAll() method of the Contentscollection to remove all items that have been added to the application.

Listing 9.9 Using the RemoveAll() Method

<script runat="server" type="text/jscript" language="JScript">

// Add two items to the collection.
Application("myItem") = "My name is Allen";
Application("yourItem") = "Your name is Reader";

// Remove all items.
Application.Contents.RemoveAll();
</script>

Application.Lock()

ASP1+

 

Syntax

Application.Lock()

Description

The Lock() method of the Application object prevents other clients from modifying any items stored in the Application object. To unlock the object, you must call the Unlock() method, or the server will unlock it either when the page has finished processing or times out.

Example

In Listing 9.10 we lock a counter item before updating it. This item could be used to count the number of users a given application has serviced.

Listing 9.10 Using the Lock() Method

<script runat="server" type="text/jscript" language="JScript">

// Initialize the counter, which should ONLY be done on the first page of
// the application.
Application("counter") = 0;

// Lock the application before incrementing the counter. Application.Lock() 

// Increment the counter. Application("counter") += 1;

// Unlock the counter for others to modify. 
Application.Unlock(); 
</script>

Application.StaticObjects

ASP1+

 

Syntax

Application.StaticObjects(name)

Description

The StaticObjects collection of the Application object stores all the objects created with <object> elements on a given ASP page. These are referenced by the name given to each instance of the elements.

Example

Listing 9.11 shows how you can grab the instance myControl from your current ASP page.

Listing 9.11 Using the StaticObjects Collection

<script runat="server" type="text/jscript" language="JScript">
Application.StaticObjects("myControl");
</script>

Application.Unlock()

ASP1+

 

Syntax

Application.Unlock()

Description

The Unlock() method of the Application object unlocks the previously locked Application object. To first lock the object, you must call the Lock() method. If you fail to call the Unlock() method, the server will unlock it when the page has finished processing or times out.

Example

In Listing 9.12 we lock a counter item before updating it. This item could be used to count the number of users a given application has serviced. After updating, we unlock it for others to access and modify.

Listing 9.12 Using the Unlock() Method


<script runat="server" type="text/jscript" language="JScript">
// Initialize the counter, which should ONLY be done on the first page of // the application.
Application("counter") = 0;

// Lock the application before incrementing the counter. Application.Lock()

// Increment the counter. Application("counter") += 1;

// Unlock the counter for others to modify. Application.Unlock(); </script>

ASPError

ASP3+

 

Syntax

Core ASP environment object

Description

The ASPError object is a core ASP environment object. Its properties and methods are used to retrieve information about errors that have occurred on a given page. This object is returned by the Server.GetLastError() method and exposes read-only properties. Table 9.2 contains a list of properties for this object.

Table 9.2 Properties of the ASPError Object

Image

Example

Listing 9.13 shows how you can write out a short description of an error that has been exposed to the ASPError object.

Listing 9.13 Using the ASPError Object

<script runat="server" type="text/jscript" language="JScript">
Response.Write(ASPError.Description); 
</script>

ASPError.ASPCode

ASP3+

 

Syntax

ASPError.ASPCode

Description

The ASPCode property of the ASPError object contains error code generated by IIS.

Example

In Listing 9.14 we write out the value of the ASPCode property.

Listing 9.14 Using the ASPCode Property

<script runat="server" type="text/jscript" language="JScript"> 
 Response.Write(ASPError.ASPCode); 
 </script>
 
 

ASPError.ASPDescription

ASP3+

 

Syntax

ASPError.ASPDescription

Description

The ASPDescription property of the ASPError object contains a more detailed description of the error returned.

Example

In Listing 9.15 we write out the value of the ASPDescription property.

Listing 9.15 Using the ASPDescription Property

<script runat="server" type="text/jscript" language="JScript"> 
Response.Write(ASPError.ASPDescription); 
</script>

ASPError.Category

ASP3+

 

Syntax

ASPError.Category 

Description

The Category property of the ASPError object indicates if the source of the error was internal to ASP, JScript, or an object.

Example

In Listing 9.16 we write out the value of the Category property.

Listing 9.16 Using the Category Property

<script runat="server" type="text/jscript" language="JScript"> 
Response.Write(ASPError.Category); 
</script>

ASPError.Column

ASP3+

 

Syntax

ASPError.Column 

Description

The Column property of the ASPError object contains the column position within the ASP file where the error occurred.

Example

In Listing 9.17 we write out the value of the Column property.

Listing 9.17 Using the Column Property


<script runat="server" type="text/jscript" language="JScript"> 
Response.Write(ASPError.Column); 
</script>

ASPError.Description

ASP3+

Syntax

ASPError.Description 

Description

The Description property of the ASPError object contains a short description of the error.

Example

In Listing 9.18 we write out the value of the Description property.

Listing 9.18 Using the Description Property

<script runat="server" type="text/jscript" language="JScript"> 
Response.Write(ASPError.Description); 
</script>

ASPError.File

ASP3+

Syntax

ASPError.File 

Description

The File property of the ASPError object contains the name of the ASP file being processed when the error occurred.

Example

In Listing 9.19 we write out the value of the File property.

Listing 9.19 Using the File Property

<script runat="server" type="text/jscript" language="JScript"> 
Response.Write(ASPError.File); 
</script>

ASPError.Line

ASP3+

Syntax

ASPError.Line

Description

The Line property of the ASPError object contains the line number on which the error occurred.

Example

In Listing 9.20 we write out the value of the Line property.

Listing 9.20 Using the Line Property

<script runat="server" type="text/jscript" language="JScript"> 
Response.Write(ASPError.Line); 
</script>

ASPError.Number

ASP3+

 

Syntax

ASPError.Number

Description

The Number property of the ASPError object contains the standard COM error code.

Example

In Listing 9.21 we write out the value of the Number property.

Listing 9.21 Using the Number Property

<script runat="server" type="text/jscript" language="JScript"> 
Response.Write(ASPError.Number); 
</script>

ASPError.Source

ASP3+

 

Syntax

ASPError.Source

Description

The Source property of the ASPError object contains the actual source code, if available, that the error occurred in.

Example

In Listing 9.22 we write out the value of the Source property.

Listing 9.22 Using the Source Property

<script runat="server" type="text/jscript" language="JScript"> 
Response.Write(ASPError.Source); 
</script>

blob() (Function)

ES2+

 

Syntax

blob(path)

Description

BLOB data represents binary large objects that can be stored in a database. This allows you to store various types of information, such as images, movie files, and sounds in the database.

Note
Be sure to consult the documentation on your specific database to see whether there are any limitations to BLOB data types.

The blob() function is used to store BLOB data in your database. This function takes the path to a BLOB file as its only parameter. Note that this path must be an absolute pathname and not a relative one.

Example

In Listing 9.23, a cursor instance has been created to perform a query on the database to find a specific row. Focus is then placed on that row and the blob() function is used to assign the data to a column. The final step in the process is to use the updateRow()

method to commit the change.

Listing 9.23 Using the blob() Function to Insert BLOB Data into a Database

<server>

// SQL statement and instance of a cursor to execute it 
var myStatement = 'SELECT * FROM family WHERE pic = null'; 
var myCursor = database.cursor(myStatement);

// Iterate through the returned rows. 
while(myCursor.next()){

// Assign 'blank.gif' in the PIC column of the returned rows. 
myCursor.pic = blob("/pictures/blank.gif"); 
myCursor.updateRow("family"); 
}

// Close the cursor and write it to the page if there was an error. 
var dbError = myCursor.close();

if(dbError) write(myCursor.close()); 
</server>

blob (Object)

ES2+

 

Syntax

Core object is created with the blob.blobImage() and blob.blobLink() methods.

Description

The top-level blob object contains methods that allow you to store and retrieve blob data in a database. BLOB data represents binary large objects that can be stored in a database. This allows you to store various types of information, such as images, movie files, and sounds in the database.

The core blob object is created when you use the methods of this object. Table 9.3 has the methods of the blob object and a description of what they do when invoked.

Table 9.3 Methods of the blob Object

Image

Example

Listing 9.24 queries a database for a specific image, creating an instance of a blob object when retrieved. The image is then written to the page using the write() and blobImage() methods. The actual tag written will be as follows:

<IMG ALT="Click" ALIGN="left" WIDTH="468" HEIGHT="60" BORDER="0" ISMAP="false">

Listing 9.24 Using the blobImage() Method to Format an <img= Tag

<server>

// Find the image you want to display.
myCursor = myConn.cursor("SELECT path FROM images WHERE img = 1");

// Write the <img> tag to the page with the following attributes set. 
write(myCursor.path.blobImage("gif", "Click", "left", 468, 60, 0, false)); // Close the cursor. 
myCursor.close(); 
</server>


blob.blobImage()

ES2+

 

Syntax

cursor.column.blobImage(fileType, altText, align, width, height, border, ismap)

Description

The blobImage() method retrieves and displays a BLOB image stored in a database. The method actually returns the HTML for the <img> tag used to display the image. The href attribute of the <img> tag references the instance of this image in memory and does not have to contain a “normal” URL of the image itself.

This method can take up to seven parameters that set the various attributes of the <img> tag. These attributes are contained in Table 9.4. At a minimum, you must pass the fileType of the image.

Table 9.4 Properties That Can Be Set with the blobImage() Method

Image

Example

Listing 9.25 queries a database for a specific image. The image is then written to the page using the write() and blobImage() methods. The actual tag written will be as follows:

<IMG ALT="Click" ALIGN="left" WIDTH="468" HEIGHT="60" BORDER="0"

ISMAP="false">

Listing 9.25 Using the blobImage() Method to Format an <img> Tag

<server>
// Find the image you want to display. 
myCursor = myConn.cursor("SELECT path FROM images WHERE img = 1");

// Write the <img> tag to the page with the following attributes set.
write(myCursor.path.blobImage("gif", "Click", "left", 468, 60, 0, false));

// Close the cursor. 
myCursor.close(); 
</server>

blob.blobLink()

ES2+

 

Syntax

cursor.column.blobLink(mimeType, text)

Description

The blobLink() method retrieves BLOB data stored in a database, stores it in memory, and creates a temporary link to it. The method actually returns the HTML for the <a> tag used to display the link. The href attribute of the <a> tag references the BLOB data type, which has been stored in a temporary memory location, and does not contain a “normal” URL of this attribute. The data is stored in memory until the user clicks the link or until 60 seconds have elapsed.

The parameters this method takes are the MIME type of the file referenced, and the text that is displayed to the user as a link.

Example

Listing 9.26 queries a database for a specific image. A link referencing the image is then written to the page using the write() and blobLink() methods. The actual tag written will be as follows:

<a href="LIVEWIRE_TEMP1">Click Here!</a>

Listing 9.26 Using the blobLink() Method to Format an <a> Tag

<server>

// Find the image you want to display.
myCursor = myConn.cursor("SELECT path FROM images WHERE img =1");

// Write the <a> tag to the page with the attributes set.
write(myCursor.path.blobLink("image/gif=, "Click Here!"));

// Close the cursor.
myCursor.close();
</server>

callC()

ES2+

 

Syntax

callC(JSFuncName, arg1, arg2, …, argN)

Description

The callC() function, which returns string values, is a top-level function that is not associated with any core object. callC() is used to call a JavaScript function that references a C function in a shared library. These libraries are the pre-built .dll files on Windows machine and .so files on Unix machines. callC() takes the JavaScript name you have assigned to the C function and any arguments the function needs as arguments.

Before you can call this function, you must register the C library using the server-side JavaScript registerCFunction(). RegisterCFunction() takes the JavaScript name with which you want to reference the function, the path to the library, and the C function name as parameters.

Example

Listing 9.27 registers an external C library, extlib.dll, that contains a function named getMyDate. The registration of this function assigns the name JSExtLib to be used within the script. If the function successfully registers, the callC() function is used to call the C function and pass it two parameters. The results are written to the user’s page. If the function does not register properly, an error is written to the user’s page.

Listing 9.27 Using a C Function with callC That Has Been Registered


<server>

// Register the library and function, assigning it a JavaScript
// function name.
var myExternalLib = registerCFunction("JSExtLib", "c:/winnt/extlib.dll",
"getMyDate")
// If the library registered without error, then call it using the
// callC function. If it failed, then write an error to the page.
if (myExternalLib) {
    write(callC("getMyDate", 1999, 2000));
}else{
    write("There was an error processing this external library function");
}

</server>

client

ES2+

 

Syntax

Core object is created with each connection of a client to your application.

Description

An instance of the client object is created with each connection of a user to your application. This object is used to maintain session variables for that user as she moves through your application’s pages. Because the object is not created until a user connects to your application, you cannot use the object on the first page of your application.

Note
The client object is created for each user’s connection to each application you have built using Server-side JavaScript, so a single user connected to two applications will have two client objects created.

The object itself is held until the user is inactive for a set period of time or the object is destroyed. At that time, the JavaScript runtime engine cleans up the object. The default timeout is ten minutes, but this can be changed by using the expiration()

method or can be destroyed manually by using the destroy() method.

client objects do not have any default properties, but properties can be created for them. Do note that because of the method used to maintain user sessions, these properties are all converted to strings. If you have created a property that must be evaluated as a numeric value, use the parseInt() and parseFloat() methods for processing.

If you must store an object as a property, you will have to create an array of objects in the project or server objects. Then you can create a property to hold the index of your object in the client object.

Example

Listing 9.28 contains a form the user fills out with her name, e-mail address, and phone number. When the Submit button is clicked, the form is sent back to itself and the script sees information being passed in. This information is then assigned to three created properties of the client object and is then written to the user’s page.

Listing 9.28 Assigning Properties to the client Object

<html>
<head>
 <title>Using the client object</title>
</head>
<body>
<server>

// See if they have submitted or just need the form.
if(request.method == "POST"){

 // Assign the client properties their values.
 client.name = request.name;
 client.email = request.email;
 client.phone = request.phone;

 // Write the user's information to the page.
 write('Hello ' + client.name + '!<br>'),
 write('Please confirm your email, ' + client.email + ', and '),
 write('phone number, ' + client.phone);
 }else{

 // If this page was called and a form was not submitted
 write('<form name="myForm" method="post">'),
 write('<table border="1"><tr><td>'),
 write('<table border="0">'),
 write('<tr align="left" valign="top">'),
 write('<td><b>Name:</b></td>'),
 write('<td><input type="text" name="name" size="30"></td>'),
 write('</tr>'),
 write('<tr align="left" valign="top">'),
 write('<td><b>E-mail:</b></td>'),
 write('<td><input type="text" name="email" size="30"></td>'),
 write('</tr>'),
 write('<tr align="left" valign="top">'),
 write('<td><b>Phone:</b></td>'),
 write('<td><input type="text" name="phone" size="30"></td>'),
 write('</tr>'),
 write('<tr align="left" valign="top">'),
 write('<td colspan="2" align="right"><input type="submit"'),
 write(' value="Submit"></td>'),
 write('</tr>'),

 write('</table>'),
 write('</td></tr></table>'),
 write('</form>'),
}
</server>
</body>
</html>

client.destroy()

ES2+

 

Syntax

client.destroy()

Description

The destroy() method of the client object explicitly destroys that instance of the object and all its associated properties. If this method is not called, the JavaScript runtime will destroy the object after 10 minutes or after the time specified with the client.expiration() method.

If you are using cookies to maintain your client object, calling the destroy() method acts in the same manner but does not remove information stored in the browser’s cookie file. To remove the cookie information, set the expiration to 0 seconds by using the client.expiration() method.

When using URL encoding to maintain the client object, the destroy() method will destroy all information with the exception that the links created before the method call will retain their properties. Because of this, good programming practice warrants calling the method at the top or bottom of a page.

Example

Listing 9.29 shows how to destroy the properties of your user’s client object.

Listing 9.29 Using the destroy() Method to Destroy the client Object Properties

<server>

// Destroy the client properties.
client.destroy()

</server>

client.expiration()

ES2+

 

Syntax

client.expiration(seconds)

Description

The expiration() method of the client object sets the number of seconds of user inactivity before the JavaScript runtime destroys all properties associated with that session. The default timeout is 10 minutes if you do not explicitly set this property. Also, this method has no effect when using URL encoding to maintain your client objects.

Note
Setting this to 0 will remove any cookies associated with the client object when using client cookies to maintain sessions.

Example

Listing 9.30 sets the destruction of the client object to occur after five minutes of inactivity.

Listing 9.30 Using the expiration() Method of the client Object

<server>

// Set the expiration to 5 minutes.
client.expiration(300)

</server>

client.property

ES2+

 

Syntax

  client.
property

Description

When a property is created for an instance of the client object, it is accomplished by passing information from a form. When you pass a form element, designated by the name attribute, to the server, it is accessible through the client.property syntax, where property is the name passed.

Example

Listing 9.31 shows how the form value zip is accessible in a server-side JavaScript script by assigning it to an instance of the client object. Once assigned, the value stored in the property is written back out to the user’s page.

Listing 9.31 Accessing a Client Property

<server>

// See if they have submitted.
if(request.method == "POST"){

 // Assign the client property its value.
  client.zip = request.zip;
}

// Write the value passed by the form to the page.
write(client.zip);
</server>

client.unwatch()

ES3+

 

Syntax

client.unwatch(property)

Description

The unwatch() method of the client object is used to turn off the watch for a particular property.

Example

Listing 9.32 shows how the unwatch() method is used to stop watching the user-defined property p.

Listing 9.32 Example of the unwatch() Method

<server>

// function that is called if property's value changes
function alertme(id, oldValue, newValue){
    write("ID (" + id + ") changed from " + oldValue + " to " + newValue);
 return newValue;
}

// See if they have submitted.
if(request.method == "POST"){

 // Assign the client property its value.
 client.zip = request.zip;
}

// watch property
client.watch("zip", alertme);

// change value
client.zip = null;

// turn off watch
client.unwatch("zip");

// change value again
client.zip = 3;

</server>

client.watch()

ES3+

 

Syntax

client.watch(property, function)

Description

The watch() method of the client object is used to turn on the watch for a particular property specified by property. Any time the specified property is changed after the watch() method has been called, the specified function is called.

Example

Listing 9.33 shows how the watch() method is used to start watching the user-defined property p.

Listing 9.33 Example of the watch() Method

<server> 
// function that is called if property's value changes
function alertme(id, oldValue, newValue){
 write("ID (" + id + ") changed from " + oldValue + " to " + newValue);
  return newValue;
}

// See if they have submitted.
if(request.method == "POST"){

  // Assign the client property its value.
  client.zip = request.zip;
}

// watch property
client.watch("zip", alertme);

 client.zip = null;

</server>

Connection

ES3+

 

Syntax

Core object is created when the DbPool.connection() method is called.

Description

The Connection object represents a given connection, pulled from a “pool”, to a database. This object has only one property, the prototype property, which you can use to add properties to the object. Table 9.5 shows the methods associated with this object.

Note
If you only need a single connection to the database and do not need to create a pool, use the database object for your connection.

Table 9.5 Methods of the Connection Object

Image

Example

Listing 9.34 creates a pool of connections to an Oracle database and initializes a connection from that pool. It takes a user’s UID and name that was passed in, runs a query (based on the UID) against the database to find that user’s information, and updates the user’s name. If a connection is not made, the error code and message is returned to the screen.

Listing 9.34 Creating and Using a Connection Object

<server>

// Assign the user submitted ID and name to the client object as properties.
client.uid = request.uid;
client.name = request.name;

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Open a connection from the pool. Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);
if(myConn.connected()){

  // Start a new SQL transaction to perform a SELECT.
  myConn.beginTransaction();
  var currRow = myConn.cursor('SELECT * FROM employees WHERE uid = ' +
 client.uid);
  // Focus on that line, change the name column for that user,
  // and update the row.
  currRow.next();
  currRow.name = client.name;
  currRow.updateRow("employees");

  // Close the cursor.
  currRow.close();

// If the connection fails, write an error message.
}else{
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
    }

</server>

Connection.beginTransaction()

ES3+

 

Syntax

connection.beginTransaction()

Description

The beginTransaction() method of the Connection object begins a new SQL transaction. This groups all the actions against the database together until the user exits the page or either the commitTransaction() or rollbackTransaction() methods are called. In the instance of the user exiting the page, the transaction is either committed or rolled back, depending on the setting of the commit flag when the DbPool object instance is created.

Example

Listing 9.35 creates a pool of connections to an Oracle database and pulls one of the connections from the pool. After the connection has been verified, the beginTransaction() method is called and a SQL query is performed. The results are formatted in a table with the SQLTable() method and written to the user’s page.

Listing 9.35 Starting a New Transaction with the beginTransaction() Method

<server>

// Assign the user submitted ID to the client object as properties.
client.uid = request.uid;

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Open a connection from the pool. Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);
if(myConn.connected()){
// Start a new transaction and write the results to a page, formatting
//  them with the SQLTable method.
myConn.beginTransaction();
write(myConn.SQLTable('SELECT * FROM employees WHERE uid >= '+client.uid));

// Commit the transaction.
myConn.commitTransaction();

// If the connection fails, write an error message
}else{
   write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
    }

</server>

Connection.commitTransaction()

ES3+

 

Syntax

connection.commitTransaction()

Description

The commitTransaction() method of the Connection object commits a new SQL transaction. This commits all the actions against the database since the last commit. If the commit is successful, 0 is returned. If a non-zero number is returned, an error is encountered. In this case, various methods of the Connection object can be used to retrieve the code and message of the error.

Example

Listing 9.36 creates a pool of connections to an Oracle database and pulls one of the connections from the pool. After the connection has been verified, the beginTransaction() method is called and a SQL query is performed. The results are formatted in a table with the SQLTable() method and written to the user’s page.

Listing 9.36 Starting a New Transaction with the commitTransaction() Method

<server>

// Assign the user submitted ID to the client object as properties.
client.uid = request.uid;

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Open a connection from the pool.  Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);
if(myConn.connected()){

 // Start a new transaction and write the results to a page, formatting
 // them with the SQLTable method.
 myConn.beginTransaction();
 write(myConn.SQLTable('SELECT * FROM employees WHERE uid >= '+client.uid));

 // Commit the transaction.
 myConn.commitTransaction();

// If the connection fails, write an error message.
}else{
    write('Error (' + myConn.majorErrorCode()+'): '' +
myConn.majorErrorMessage();
      }

</server>

Connection.connected()

ES3+

 

Syntax

connection .connected()

Description

The connected() method of the Connection object tells if the pool of connections to the database is still connected.

Example

Listing 9.37 creates a pool of connections and pulls a connection from the pool for processing. If the connection is made, any code within that section is executed. If the connection fails, the error is written to the page.

Listing 9.37 Testing a Connection with the connected() Method

<server>

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Open a connection from the pool.  Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);
if (myConn.connected()) {

    // You are connected, so perform any tasks here.

}else{

    // There was an error connecting to the database.
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

</server>

Connection.cursor()

ES3+

 

Syntax

connection.cursor( (sql)

connection.cursor( sql, boolean)

Description

The cursor() method of the Connection object creates a Cursor object that can be used to run SQL queries against the database. The method takes the sql statement as a parameter, as well as an optional boolean value that specifies whether the cursor is updateable.

Example

Listing 9.38 shows how you would run a query against the database using the cursor() method. The while loop is used to write the results to the user’s page.

Listing 9.38 Using the cursor() Method to Run a Query Against the Database

<server>

// Set the query to run.
var mySQL = myConn.cursor('SELECT name,title FROM employees'),

// Iterate through the results and write them to the page.
while(mySQL.next()){
    write(mySQL.name + ': ' + mySQL.title + '<br>'),
}

</server>

Connection.execute()

ES3+

 

Syntax

connection.execute( statement)

Description

The execute() method of the Connection object enables your application to execute a DDL (Data Definition Language) or DML (Data Manipulation Language) query, which does not return a Cursor, supported by your database. This includes statements such as CREATE, ALTER, and DROP.

Example

Listing 9.39 deletes all rows with a UID less than the number passed to the script.

Listing 9.39 Using the execute() Method to Run DML Queries

<server>

// Assign the UID passed to the client object
client.uid = request.uid;

// Execute a DELETE based on the UID passed
myConn.execute('DELETE FROM employees WHERE uid < ' + client.uid);

</server>

Connection.majorErrorCode()

ES3+

 

Syntax

connection .majorErrorCode()

Description

The majorErrorMessage() method of the Connection object contains the ODBC or database numeric error code that is returned if an error occurs.

Example

Listing 9.40 shows how you would create a pool of connections, pull a connection from it, and test for the connection. If the test fails, the majorErrorCode() is used when writing the error to the page.

Listing 9.40 Using majorErrorCode() to Retrieve a Database Connection Error

<server>

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Open a connection from the pool. Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);

if (myConn.connected()) {

    // You are connected, so perform any tasks here.

}else{

    // There was an error connecting to the database.
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

</server>

Connection.majorErrorMessage()

ES3+

 

Syntax

connection .majorErrorMessage()

Description

The majorErrorMessage() method of the Connection object contains the ODBC or database string error message that is returned if an error occurs.

Example

Listing 9.41 shows how you would create a pool of connections, pull a connection from it, and test for the connection. If the test fails, the majorErrorMessage() is used when writing the error to the page.

Listing 9.41 Using majorErrorMessage() to Retrieve a Database Connection Error

<server>

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Open a connection from the pool. Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);

if (myConn.connected()) {

    // You are connected, so perform any tasks here.

}else{

    // There was an error connecting to the database
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

</server>

Connection.minorErrorCode()

ES3+

 

Syntax

connection .minorErrorCode()

Description

The minorErrorMessage() method of the Connection object contains the secondary ODBC or database numeric error code that is returned if an error occurs.

Example

Listing 9.42 shows how you would create a pool of connections, pull a connection from it, and test for the connection. If the test fails, the minorErrorCode() is used when writing the secondary error to the page.

Listing 9.42 Using minorErrorCode() to Retrieve a Secondary Database Connection Error

<server>

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Open a connection from the pool. Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);

if (myConn.connected()) {

    // You are connected, so perform any tasks here.
}else{

    // There was an error connecting to the database.
    write('Error ('+myConn.minorErrorCode()+'): '+myConn.minorErrorMessage);
}

</server>

Connection.minorErrorMessage()

ES3+

 

Syntax

connection .minorErrorMessage()

Description

The minorErrorMessage() method of the Connection object contains the secondary ODBC or the database string error message that is returned if an error occurs.

Example

Listing 9.43 shows how you would create a pool of connections, pull a connection from it, and test for the connection. If the test fails, the minorErrorMessage() is used when writing the secondary error to the page.

Listing 9.43 Using minorErrorMessage() to Retrieve a Secondary Database Connection Error

<server>

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Open a connection from the pool. Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);

if (myConn.connected()) {

    // You are connected, so perform any tasks here.

}else{

    // There was an error connecting to the database.
    write('Error ('+myConn.minorErrorCode()+'): '+myConn.minorErrorMessage);
}

Connection.prototype

ES3+

 

Syntax

connection .prototype. method = name

connection .prototype. property = value

Description

The prototype property of the Connection object allows you to add methods and properties to the Connection object. If you are adding a method, you set the instance equal to the name of the method you have defined.

Example

Listing 9.44 creates a new property and method of the Connection object. An instance is created and the new property is set. The new method is then called to verify the property and, if it is incorrect (which it is), an error message is written to the page.

Listing 9.44 Using the prototype Property to Create a New Property and Method

<server>

// Define the method that we prototyped.
function verifyODBC(){

    // Check to see if the type property we added is set to a valid value.
    if(this.type == "ODBC"){
       return true;
    }else{
       return false;
    }
}

// Create a new property and method of the Connection object.
Connection.prototype.type = null;
Connection.prototype.isODBC = verifyODBC;

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Open a connection from the pool.
var myConn = myPool.connection('Employees', 15);

// Using the prototype we defined, assign the type property.
myConn.type = "Oracle";
// Check the type of the connection to see if it is valid.
if(myConn.isODBC()){
    write(myConn + " has a valid type of " + myConn.type);
}else{
    write(myConn + " has an invalid type of " + myConn.type);
}

</server>

Connection.release()

ES3+

 

Syntax

connection .release()

Description

The release() method of the Connection object returns the connection to the DbPool instance after all cursors have been closed. If you do not close the cursor, the connection will remain until it times out or the variable holding your connection, assuming you assigned it to one, goes out of scope. Depending on how you have written your application, this can happen when the application is stopped, the Web server is stopped, or when control leaves the HTML page.

Example

Listing 9.45 shows a pool being created, a connection being pulled from the pool, and a query run against the database. When the cursor is closed, the connection is released.

Listing 9.45 Releasing a Connection Back to the Pool Using the release() Method

<server>

// Assign the user submitted ID and name to the client object as properties.
client.uid = request.uid;
client.name = request.name;

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Open a connection from the pool. Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);
if(myConn.connected()){

    // Start a new SQL transaction to perform a SELECT.
    myConn.beginTransaction();
    var currRow = myConn.cursor('SELECT * FROM employees WHERE uid = ' +
    client.uid);

    // Focus on that line, change the name column for that user,
    // and update the row.
    currRow.next();
    currRow.name = client.name;
    currRow.updateRow("employees");

    // Close the cursor.
    currRow.close();

// If the connection fails, write an error message.
}else{
   write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

// Release the connection.
myConn.release();

</server>

Connection.rollbackTransaction()

ES3+

 

Syntax

connection.rollbackTransaction()

Description

The rollbackTransaction() method of the Connection object will undo all actions performed since the last beginTransaction() method call.

Example

Listing 9.46 takes a commit field sent to the application from the user. If this evaluates to true, the transaction is committed. If not, it is rolled back.

Listing 9.46 Rolling Back a Transaction with the rollbackTransaction() Method

<server>

// See if the user wants to commit the last transaction.
client.commit = request.commit;
if(client.commit = "YES"){

  // Commit the transaction.
  myConn.commitTransaction();

}else{

    // Rollback the transaction.
    myConn.rollbackTransaction();
}

</server>

Connection.SQLTable()

ES3+

 

Syntax

connection.SQLTable((sql)

Description

The SQLTable() method of the Connection object takes a sql SELECT statement as a parameter and executes a query through the connection from which it was called. It returns the result formatted in an HTML table for easy writing to a client’s page. This is a simple table in the following format:

<table border="1">
<tr>
<th>column 1 </th>
<th>column 2 </th>

<th>column N </th>
</tr>
<tr>
<td>value 1 of column 1 </td>
<td>value 1 of column 2 </td>

<td>value 1 of column N </td>
</tr>
<tr>
<td>value 2 of column 1 </td>
<td>value 2 of column 2 </td>

<td>value 2 of column N </td>
</tr>

</table>

Example

Listing 9.47 runs a user passed query and formats the result using the SQLTable() method. This information is then written to the user’s page.

Listing 9.47 Using the SQLTable() Method to Format the Results of a SELECT Query

<server>

// Assign the user submitted query to the client object.
client.sql = request.sql;

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Open a connection from the pool. Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);
if(myConn.connected()){

  // Start a new transaction and write the results to a page, formatting
  // them with the SQLTable method.
  myConn.beginTransaction();
  write(myConn.SQLTable(client.sql));

  // Commit the transaction.
  myConn.commitTransaction();

// If the connection fails, write an error message.
}else{
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

// Release the connection.
myConn.release();

</server>

Connection.storedProc()

ES3+

 

Syntax

connection.storedProc(procName)

connection.storedProc(procName, arg1, arg2, …, argN)

Description

The storedProc() method of the Connection object creates a Stproc object that allows you to execute a database-specific stored procedure using the connection from which it was invoked.

As shown in the syntactical definition, you can also pass any arguments needed to the method for processing. If you are using a stored procedure that requires arguments, or if you want to have the procedure run using default arguments, you must pass /Default/ as the argument. The following shows an example of passing a default value:

var myStproc = myConn.storedProc("sp_employees", "/Default/");

The scope of this procedure is restricted to the current page. Any methods of the Stproc object must be invoked on the current page. If this is not possible, a new object will have to be created on subsequent pages to access the properties needed.

Example

Listing 9.48 creates a pool of connections and pulls one of the connections. When the connection has been verified, the storedProc() method is used to invoke the fictitious sp_employees stored procedure.

Listing 9.48 Using the storedProc() Method to Invoke a Stored Procedure on a Database

<server>

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Open a connection from the pool.  Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);
if(myConn.connected()){

  myConn.beginTransaction();

  // Run the stored procedure.
  var myStproc = myConn.storedProc("sp_employees");

  // Commit the transaction.
  myConn.commitTransaction();

// If the connection fails, write an error message.
}else{
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}
// Release the connection.
myConn.release();

</server> >

Connection.toString()

ES3+

 

Syntax

connection.toString()

Description

The toString() method of the Connection object returns a text value of the object. When invoked on an instance of a Connection object, the string is returned in the following format:

"dbName" "uid" "dbType" "dbInstance"

If the parameter is unknown, an empty string is returned. Table 9.6 contains the value of these returned values.

Table 9.6 Return Values of thetoString() Method

Image

Example

Listing 9.49 creates an instance of the Connection object. Once created, the write() method is used to write its string value to the page.

Listing 9.49 Write the Results of Calling the toString() Method to a Page

<server>

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Open a connection from the pool. Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);
if(myConn.connected()){

  // Write the string value of the object to the page.
  write(myConn.toString());

// If the connection fails, write an error message.
}else{
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

// Release the connection.
myConn.release();

</server>

Connection.unwatch()

ES3+

 

Syntax

connection.unwatch(property)

Description

The unwatch() method of the Connection object is used to turn off the watch for a particular property.

Example

Listing 9.50 shows how the unwatch() method is used to stop watching the user-defined property p.

Listing 9.50 Example of the unwatch() Method

<server>

// Define the method that we prototyped.
function verifyODBC(){
    // Check to see if the type property we added is set to a valid value.
    if(this.type == "ODBC"){
       return true;
    }else{
       return false;
    }
}

// Function that is called if property's value changes.
function alertme(id, oldValue, newValue){
    write("ID (" + id + ") changed from " + oldValue + " to " + newValue);
    return newValue;
}

// Create a new property and method of the Connection object.
Connection.prototype.type = null;
Connection.prototype.isODBC = verifyODBC;

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Open a connection from the pool.
var myConn = myPool.connection('Employees', 15);

// Using the prototype we defined, assign the type property.
myConn.type = "Oracle";

// Watch the type property.
myConn.watch("type", alertme);

// Check the type of the connection to see if it is valid.
if(myConn.isODBC()){
    write(myConn + " has a valid type of " + myConn.type);
}else{
    write(myConn + " has an invalid type of " + myConn.type);
}

// change value
myConn.type = null;

// turn off watch
myConn.unwatch("type");

// change value again
myConn.type = "Sybase";

</server>

Connection.watch()

ES3+

 

Syntax

connection.watch(property, function)

Description

The watch() method of the Connection object is used to turn on the watch for a particular property specified by property. Any time the specified property is changed after the watch() method has been called, the specified function is called.

Example

Listing 9.51 shows how the watch() method is used to start watching the user-defined property p.

Listing 9.51 Example of the watch() Method

<server>

// Define the method that we prototyped.
function verifyODBC(){

  // Check to see if the type property we added is set to a valid value.
  if(this.type == "ODBC"){
      return true;
  }else{
       return false;
    }
}

// Function that is called if property's value changes.
function alertme(id, oldValue, newValue){
    write("ID (" + id + ") changed from " + oldValue + " to " + newValue);
    return newValue;
}

// Create a new property and method of the Connection object.
Connection.prototype.type = null;
Connection.prototype.isODBC = verifyODBC;

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Open a connection from the pool.
var myConn = myPool.connection('Employees', 15);

// Using the prototype we defined, assign the type property.
myConn.type = "Oracle";
// Watch the type property.
myConn.watch("type", alertme);

// Check the type of the connection to see if it is valid.
if(myConn.isODBC()){
  write(myConn + " has a valid type of " + myConn.type);
}else{
  write(myConn + " has an invalid type of " + myConn.type);
}

// change value
myConn.type = null;

</server>

Cursor

ES2+

 

Syntax

connection.cursor()

database.cursor()

Description

The Cursor object is a core object created when the cursor() method of the Connection or database object is called. A database query is said to return a cursor, so this object contains references to the rows returned from a query.

When working with cursor objects, you should explicitly close them using the close() method when you are finished. Not doing so will cause the JavaScript runtime to hold the cursor in memory until the connection or pool to which the cursor was tied goes out of scope.

The Cursor object has several methods and properties associated with it. These are listed in Table 9.7.

Table 9.7 Properties and Methods of the Cursor Object

Image

Example

Listing 9.52 takes a UID, passed as an area code, that is assigned to the client object. A pool of connections is then opened to the database, and one of the connections is pulled to run the query. The results of the query are stored in a Cursor object and are iterated through use of the next() method. After all rows have been updated with the new area code, the cursor is closed and the connection is released.

Listing 9.52 Using the Cursor Object

<server>

// Assign the user submitted ID and area code to the client object
// as properties.
client.uid = request.uid;
client.areacode = request.areacode;

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Open a connection from the pool. Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);
if(myConn.connected()){

  // Start a new SQL transaction to perform a SELECT.
  myConn.beginTransaction();
  var currRow = myConn.cursor('SELECT areacode FROM employees WHERE uid >= '
 + client.uid);

  // For all the lines that matched, update the area code.
  while(currRow.next()){
     currRow.areacode = client.areacode;
     currRow.updateRow("employees");
  }

  // Close the cursor.
 currRow.close();

// If the connection fails, write an error message.
}else{
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

// Release the connection.
myConn.release();

</server>

Cursor.close()

ES2+

 

Syntax

cursor.close()

Description

The close() method of the Cursor object closes the cursor and frees all memory that had been used to store its information. If successful, the method returns 0, otherwise it returns an error code that can be obtained by using the majorErrorCode() and majorErrorMessage() methods of the Connection or database objects.

Example

Listing 9.53 creates a cursor and then closes it.

Listing 9.53 Closing a Cursor with the close() Method

<server>

// Create cursor
var currRow = myConn.cursor('SELECT areacode FROM employees WHERE uid >= '
+ client.uid);
// Close the cursor
currRow.close();

</server>

Cursor.columnName

ES2+

 

Syntax

cursor.columnName

Description

The columnName property of the Cursor object is an array of objects that corresponds to the name of the columns in the cursor.

Example

Listing 9.54 shows a cursor object being created. The various values are then written to the page using the columnName property as their reference.

Listing 9.54 Using the columnName Property

<server>

var currRow = myConn.cursor('SELECT areacode,phone,name FROM employees'),

// Write each person's name and phone number to the page in the form:
// "<name>'s phone number is (<areacode>) <phone>"
while(currRow.next()){
    write(currRow.name + "'s phone number is (" + currRow.areacode + ") ");
    write(currRow.phone + "<br>");
}

// Close the cursor
currRow.close();

</server>

Cursor.columnName()

ES2+

 

Syntax

cursor.columnName((num)

Description

The columnName() method of the Cursor object takes the zero-based indexed number location,num, passed to the method and returns the name of the column in that location. Note that these names are not returned in any specific order unless you order them as such. Successive calls to the method, however, will return all the columns. See the example for more information on this.

Example

Listing 9.55 has two cursors. One of the cursors returns specific column names and the other returns all columns. See the comments in the code for the output.

Listing 9.55 Using the columnName() Method to Return the Names of the Columns in a Table

<server>

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Open a connection from the pool. Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);
if(myConn.connected()){

  // Start a new SQL transaction to perform a SELECT.
  myConn.beginTransaction();
  var currRow1 = myConn.cursor('SELECT areacode,phone FROM employees
WHERE uid >= 100'),
  var currRow2 = myConn.cursor('SELECT * FROM employees WHERE uid >= 100'),

  // Writes 'areacode', from the first cursor, to the page.
  write(currRow1.columnName(0));

  // Writes 'phone', from the first cursor, to the page.
  write(currRow1.columnName(1));

  // Writes all column names stored in the second cursor to the page.
  // This will include 'areacode' and 'phone' as well as any other
  // columns.
  for(var i = 0; i <= currRow2.columns(); i++){
    write(currRow2.columnName(i));
  }

  // Close the cursors.
  currRow1.close();
  currRow2.close();
// If the connection fails, write an error message.
}else{
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

// Release the connection.
myConn.release();

</server>

Cursor.columns()

ES2+

 

Syntax

cursor.columns()

Description

The columns() method of the Cursor object returns the number of columns in the cursor on which it is invoked. If the SQL string that was passed to create the cursor specified a set number of columns to return, this is the number returned by the method.

Example

Listing 9.56 shows how you can return all the column names of the columns in your cursor.

Listing 9.56 Using the columns() Method to Determine How Many Columns Are in the Cursor Before Writing Them to the Page

<server>

var currRow = myConn.cursor('SELECT * FROM employees'),

// Writes all column names stored in the cursor to the page.
for(var i = 0; i <= currRow.columns(); i++){
    write(currRow.columnName(i));
}

// Close the cursors
currRow.close();

</server>

Cursor.deleteRow()

ES2+

 

Syntax

cursor.deleteRow(table)

Description

The deleteRow() method of the Cursor object uses an updateable cursor and deletes the current row in the specified table of the Cursor object. If the delete was successful, 0 is returned; otherwise it returns an error code that can be obtained by using the majorErrorCode() and majorErrorMessage() methods of the Connection or database objects.

Example

Listing 9.57 creates a Cursor object and selects all instances of a given id. The deleteRow() method is then used to delete each of these instances.

Listing 9.57 Deleting a Row from the Cursor Using the deleteRow() Method

<server>

// Assign the user submitted ID to the client object as properties.
client.uid = request.uid;

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Open a connection from the pool. Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);
if(myConn.connected()){

  // Start a new SQL transaction to perform a SELECT.
  myConn.beginTransaction();
var currRow = myConn.cursor('SELECT * FROM employees WHERE uid = '
  + client.uid, true);
  

// Delete each row in the cursor.
 while(currRow.next(){
     currRow.delete("employees");
 }

  // Close the cursor.
  currRow.close();
// If the connection fails, write an error message.
}else{
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

</server>

Cursor.insertRow()

ES2+

 

Syntax

cursor.insertRow((table)

Description

The insertRow() method of the Cursor object uses an updateable cursor and inserts a new row in the specified table of the Cursor object. If the insert was successful, 0 is returned; otherwise, it returns an error code that can be obtained by using the majorErrorCode() and majorErrorMessage() methods of the Connection or database objects.

Example

Listing 9.58 creates a Cursor object and selects all rows. The insertRow() method is then used to insert a new row with three specified columns.

Listing 9.58 Inserting a Row from the Cursor Using the insertRow() Method

<server>

// Assign the user submitted ID to the client object as properties.
client.uid = request.uid;
client.name = request.name;
client.pwd = request.pwd;

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");
// Open a connection from the pool. Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);
if(myConn.connected()){

  // Start a new SQL transaction to perform a SELECT. Notice the
  // cursor is updateable.
  myConn.beginTransaction();
  var currRow = myConn.cursor('SELECT uid,name,pwd FROM employees', true);

  // Assign values to the columns and insert a new row.
  currRow.uid = client.uid;
  currRow.name = client.name;
  currRow.pwd = client.pwd;
  currRow.insertRow("employees");
  myConn.commitTransaction();

  // Close the cursor and release the connection.
  currRow.close();
  myConn.release();

// If the connection fails, write an error message.
}else{
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

</server>

Cursor.next()

ES2+

 

Syntax

cursor.next()

Description

The next() method of the Cursor object moves the point in the current row to the next row in the cursor. This method is used to iterate through each of the rows returned by the cursor. This method returns true, unless it is the last row of the cursor, at which time it returns false.

Example

Listing 9.59 creates an instance of the Cursor object and iterates through its results, deleting each row. This is performed by using the next()method.

Listing 9.59 Using the next() Method to Iterate Through the Rows in a Cursor

<server>

var currRow = myConn.cursor('SELECT * FROM employees WHERE uid <= 200'),

// Delete each row in the cursor.
while(currRow.next(){
    currRow.delete("employees");
}

// Close the cursor.
currRow.close();

</server>

Cursor.prototype

ES2+

 

Syntax

cursor.prototype.method = name

cursor.prototype.property = value

Description

The prototype property of the Cursor object allows you to create new properties and methods of the object. If you are adding a method, you set the instance equal to the name of the method you have defined.

Example

Listing 9.60 creates a new property and method of the Cursor object. An instance is created and the new property is set. The new method is then called to verify the property, and, if it is incorrect, an error message is written to the >page.

Listing 9.60 Using the prototype Property to Create a New Property and Method

<server>

// Define the method that we prototyped.
function verifySELECT(){

    // Check to see if the type property we added is set to a valid value.
    if(this.type == "SELECT"){
       return true;
    }else{
       return false;
    }
}

// Create a new property and method of the Cursor object.
Cursor.prototype.type = null;
Cursor.prototype.isSELECT = verifySELECT;

// Create a pool of connections, a connection, and a cursor.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");
var myConn = myPool.connection('Employees', 15);
var currRow = myConn.cursor('SELECT * FROM employees'),

// Using the prototype we defined, assign the type property.
currRow.type = "SELECT";

// Check the type of the connection to see if it is valid.
if(currRow.verifySELECT()){
    write(currRow + " has a valid type of " + currRow.type);
}else{
    write(currRow + " has an invalid type of " + currRow.type);
}

</server>

Cursor.unwatch()

ES3+

 

Syntax

cursor.unwatch(property)

Description

The unwatch() method of the Cursor object is used to turn off the watch for a particular property.

Example

Listing 9.61 shows how the unwatch() method is used to stop watching the user-defined property p.

Listing 9.61 Example of the unwatch() Method

<server>

// Define the method that we prototyped.
function verifySELECT(){
 // Check to see if the type property we added is set to a valid value.
  if(this.type == "SELECT"){
     return true;
  }else{
       return false;
  }
}

// Function that is called if property's value changes.
function alertme(id, oldValue, newValue){
    write("ID (" + id + ") changed from " + oldValue + " to " + newValue);
    return newValue;
}

// Create a new property and method of the Cursor object.
Cursor.prototype.type = null;
Cursor.prototype.isSELECT = verifySELECT;

// Create a pool of connections, a connection, and a cursor.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");
var myConn = myPool.connection('Employees', 15);
var currRow = myConn.cursor('SELECT * FROM employees'),

// Using the prototype we defined, assign the type property.
currRow.type = "SELECT";

// watch property
currRow.watch("type", alertme);

// Check the type of the connection to see if it is valid.
if(currRow.verifySELECT()){
    write(currRow + " has a valid type of " + currRow.type);
}else{
    write(currRow + " has an invalid type of " + currRow.type);
}

// change value
currRow.type = "DELETE";

// turn off watch
currRow.unwatch("type");

// change value again
currRow.type = "INSERT";

</server>

Cursor.updateRow()

ES2+

 

Syntax

cursor.updateRow((table)

Description

The updateRow() method of the Cursor object uses an updateable cursor and updates the current row in the specified table of the cursor object. If the insert was successful,0 is returned; otherwise, it returns an error code that can be obtained by using the majorErrorCode() and majorErrorMessage() methods of the Connection or database objects.

Example

Listing 9.62 creates a Cursor object and selects all rows. The updateRow() method is then used to update the current row with three specified values.

Listing 9.62 Updating a Row from the Cursor Using the updateRow() Method

<server>

// Assign the user submitted ID to the client object as properties.
client.uid = request.uid;
client.name = request.name;
client.pwd = request.pwd;

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Open a connection from the pool. Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);
if(myConn.connected()){

  // Start a new SQL transaction to perform a SELECT. Notice the
  // cursor is updateable.
  myConn.beginTransaction();
  var currRow = myConn.cursor('SELECT uid,name,pwd FROM employees WHERE uid = '
+ client.uid, true);

    // Select the row and assign values to the columns.
    currRow.next();
    currRow.uid = client.uid;
    currRow.name = client.name;
    currRow.pwd = client.pwd;
    currRow.updateRow("employees");

    myConn.commitTransaction();

    // Close the cursor and release the connection.
    currRow.close();
    myConn.release();

// If the connection fails, write an error message.
}else{
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

</server>

Cursor.watch()

ES3+

 

Syntax

cursor.watch(property, function)

Description

The watch() method of the Cursor object is used to turn on the watch for a particular property specified by property. Any time the specified property is changed after the watch() method has been called, the specified function is called.

Example

Listing 9.63 shows how the watch() method is used to start watching the user-defined property p.

Listing 9.63 Example of the watch() Method

<server>

// Define the method that we prototyped.
function verifySELECT(){

    // Check to see if the type property we added is set to a valid value.
    if(this.type == "SELECT"){
       return true;
    }else{
       return false;
    }
}

// Function that is called if property's value changes.
function alertme(id, oldValue, newValue){
    write("ID (" + id + ") changed from " + oldValue + " to " + newValue);
    return newValue;
}

// Create a new property and method of the Cursor object.
Cursor.prototype.type = null;
Cursor.prototype.isSELECT = verifySELECT;

// Create a pool of connections, a connection, and a cursor.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");
var myConn = myPool.connection('Employees', 15);
var currRow = myConn.cursor('SELECT * FROM employees'),

// Using the prototype we defined, assign the type property.
currRow.type = "SELECT";

// watch property
currRow.watch("type", alertme);

// Check the type of the connection to see if it is valid.
if(currRow.verifySELECT()){
    write(currRow + " has a valid type of " + currRow.type);
}else{
    write(currRow + " has an invalid type of " + currRow.type);
}

// change value
currRow.type = "DELETE";

</server>

database

ES2+

 

Syntax

Core object is created when the database.connect() method is called.

Description

The database object represents a given connection to a database. This object has only one property, the prototype property, which you can use to add properties to the object. Table 9.8 lists the methods associated with this object.

Table 9.8 Methods of the database Object

Image

Example

Listing 9.64 creates a connection to an Oracle database. It takes a user’s UID and name that was passed in, runs a query (based on the UID) against the database to find that user’s information, and updates her name. If a connection is not made, the error code and message are returned to the screen.

Listing 9.64 Creating and Using a database Object

<server>

// Assign the user submitted ID and name to the client object as properties.
client.uid = request.uid;
client.name = request.name;

// Open a connection.
var myConn = database.connect("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

if(myConn.connected()){

  // Start a new SQL transaction to perform a SELECT.
  myConn.beginTransaction();
  var currRow = myConn.cursor('SELECT * FROM employees WHERE uid = '
 + client.uid);

  // Focus on that line, change the name column for that user,
  // and update the row.
  currRow.next();
  currRow.name = client.name;
  currRow.updateRow("employees");
  myConn.commitTransaction();

  // Close the cursor and drop the connection.
  currRow.close();
  myConn.disconnect();

// If the connection fails, write an error message.
}else{
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

</server>

database.beginTransaction()

ES2+

 

Syntax

database.beginTransaction()

Description

The beginTransaction() method of the database object begins a new SQL transaction. This groups all the actions against the database together until the user exits the page or either the commitTransaction() or rollbackTransaction() methods are called. In the instance of the user exiting the page, the transaction is either committed or rolled back, depending on the setting of the commit flag when the database object instance is created.

Example

Listing 9.65 creates a connection to an Oracle database. After the connection has been verified, the beginTransaction() method is called and a SQL query is performed. The results are formatted in a table with the SQLTable() method and written to the user’s page.

Listing 9.65 Starting a New Transaction with the beginTransaction() Method

<server>

// Assign the user submitted ID to the client object as properties.
client.uid = request.uid;

// Open a connection.
var myConn = database.connect("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

if(myConn.connected()){

  // Start a new transaction and write the results to a page, formatting
  // them with the SQLTable method.
  myConn.beginTransaction();
  write(myConn.SQLTable('SELECT * FROM employees WHERE uid >= ' + client.uid));

  // Commit the transaction.
  myConn.commitTransaction();

// If the connection fails, write an error message.
}else{
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

</server>

database.commitTransaction()

ES2+

 

Syntax

database.commitTransaction()

Description

The commitTransaction() method of the database object commits a new SQL transaction. This commits all the actions against the database since the last commit. If the commit is successful, 0 is returned. If a non-zero number is returned, an error was encountered. In this case, you can use the various methods of the database object to retrieve the code and message of the error.

Example

Listing 9.66 creates a connection to an Oracle database. After the connection has been verified, the beginTransaction() method is called and a SQL query is performed. The results are formatted in a table with the SQLTable() method and written to the user’s page.

Listing 9.66 Starting a New Transaction with the commitTransaction() Method

<server>

// Assign the user submitted ID to the client object as properties.
client.uid = request.uid;

// Open a connection.
var myConn = database.connect("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

if(myConn.connected()){

  // Start a new transaction and write the results to a page, formatting
  // them with the SQLTable method.
  myConn.beginTransaction();
  write(myConn.SQLTable('SELECT * FROM employees WHERE uid >= ' + client.uid));

  // Commit the transaction.
  myConn.commitTransaction();

// If the connection fails, write an error message.
}else{
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

</server>

database.connect()

ES2+

 

Syntax

database.connect(dbType, dbInstance, uid, pwd, dbName)

database.connect(dbType, dbInstance, uid, pwd, dbName, maxConn)

database.connect(dbType, dbInstance, uid, pwd, dbName, maxConn, commitFlag)

Description

The connect method of the database object is the actual method that connects to a database given the parameters passed. Before you open a connection to a database and have the ability to run queries against it, you should create an instance of this object. Each parameter is defined in Table 9.9.

Table 9.9 Parameters of the connect Method

Image

Depending on your database, it is possible to create an instance of this object by passing a limited set of these parameters. See your database documentation for this information.

Example

Listing 9.67 creates a connection to an Oracle database. It takes a user’s UID and name that was passed in, runs a query (based on the UID) against the database to find that user’s information, and updates her name. If a connection is not made, the error code and message are returned to the screen.

Listing 9.67 Connecting to a Database Using the connect() Method

<server>

// Assign the user submitted ID and name to the client object as properties.
client.uid = request.uid;
client.name = request.name;

// Open a connection.
var myConn = database.connect("ORACLE","mySID","myApp","appsPWD","myTNS",true);

if(myConn.connected()){

  // Start a new SQL transaction to perform a SELECT.
  myConn.beginTransaction();
  var currRow = myConn.cursor('SELECT * FROM employees WHERE uid = '
 + client.uid);

  // Focus on that line, change the name column for that user,
  // and update the row.
  currRow.next();
  currRow.name = client.name;
  currRow.updateRow("employees");
  myConn.commitTransaction();

  // Close the cursor and the connection.
  currRow.close();
  myConn.disconnect();

// If the connection fails, write an error message.
}else{
  write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

</server>

database.connected()

ES2+

 

Syntax

database.connected()

Description

The connected() method of the database object tells whether the connection to the database is still active.

Example

Listing 9.68 creates a connection to a database. If the connection is made, any code within that section is executed. If the connection fails, the error is written to the page.

Listing 9.68 Testing a Connection with the connected() Method

<server>

// Open a connection.
var myConn = database.connect("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");
if (myConn.connected()) {

  // You are connected, so perform any tasks here.

}else{

  // There was an error connecting to the database.
  write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

</server>

database.cursor()

ES2+

 

Syntax

database.cursor(sql)

database.cursor(sql, boolean)

Description

The cursor() method of the database object creates a Cursor object that can be used to run SQL queries against the database. The method takes the sql statement as a parameter, as well as an optional boolean value that specifies whether the cursor is updateable.

Example

Listing 9.69 shows how you would run a query against the database using the cursor() method. The while loop is used to write the results to the user’s page.

Listing 9.69 Using the cursor() Method to Run a Query Against the Database

<server>

// Set the query to run.
var mySQL = myConn.cursor('SELECT name,title FROM employees'),

// Iterate through the results and write them to the page.
while(mySQL.next()){
    write(mySQL.name + ': ' + mySQL.title + '<br>'),
}

</server>

database.disconnect()

ES2+

 

Syntax

database.disconnect()

Description

The disconnect method of the database object disconnects a connection to a database.

Example

Listing 9.70 creates a connection to an Oracle database. It takes a user’s UID and name that was passed in, runs a query (based on the UID) against the database to find that user’s information, and updates her name. If a connection is not made, the error code and message are returned to the screen. After the processing has been completed, the connection is dropped using the disconnect() method.

Listing 9.70 Disconnecting from a Database Using the disconnect() Method

<server>

// Assign the user submitted ID and name to the client object as properties.
client.uid = request.uid;
client.name = request.name;

// Open a connection.
var myConn = database.connect("ORACLE","mySID","myApp","appsPWD","myTNS",true);

if(myConn.connected()){

  // Start a new SQL transaction to perform a SELECT.
  myConn.beginTransaction();
  var currRow = myConn.cursor('SELECT * FROM employees WHERE uid = '
  + client.uid);

  // Focus on that line, change the name column for that user,
  // and update the row.
  currRow.next();
  currRow.name = client.name;
  currRow.updateRow("employees");
  myConn.commitTransaction();

  // Close the cursor and the connection.
  currRow.close();
  myConn.disconnect();
// If the connection fails, write an error message.
}else{
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

</server>

database.execute()

ES2+

 

Syntax

database.execute(statement)

Description

The execute() method of the database object enables your application to execute a DDL (Data Definition Language) or DML (Data Manipulation Language) query, which does not return a Cursor, supported by your database. This includes statements such as CREATE, ALTER, and DROP.

Example

Listing 9.71 deletes all rows with a UID less than the number passed to the script.

Listing 9.71 Using the execute() Method to Run DML Queries

<server>

// Assign the UID passed to the client object.
client.uid = request.uid;

// Execute a DELETE based on the UID passed.
myConn.execute('DELETE FROM employees WHERE uid < ' + client.uid);

</server>

database.majorErrorCode()

ES2+

Syntax

database.majorErrorCode()

Description

The majorErrorCode() method of the database object contains the ODBC or database numeric error code that is returned if an error occurs.

Example

Listing 9.72 shows how you would create a connection and test for a successful connection. If the test fails, the majorErrorCode() is used when writing the error to the page.

Listing 9.72 Using majorErrorCode() to Retrieve a Database Connection Error

<server>

// Open a connection.
var myConn = database.connect("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

if (myConn.connected()) {

    // You are connected, so perform any tasks here.

}else{

    // There was an error connecting to the database.
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

</server>

database.majorErrorMessage()

ES2+

Syntax

database.majorErrorMessage()

Description

The majorErrorMessage() method of the database object contains the ODBC or database string error message that is returned if an error occurs.

Example

Listing 9.73 shows how you would create a connection and test for a successful connection. If the test fails, the majorErrorMessage() is used when writing the error to the page.

Listing 9.73 Using majorErrorMessage() to Retrieve a Database Connection Error

<server>

// Open a connection.
var myConn = database.connect("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

if (myConn.connected()) {

    // You are connected, so perform any tasks here.

}else{

    // There was an error connecting to the database.
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

</server>

database.minorErrorCode()

ES2+

 

Syntax

database.minorErrorCode()

Description

The minorErrorCode() method of the database object contains the secondary ODBC or database numeric error code that is returned if an error occurs.

Example

Listing 9.74 shows how you would create a connection and test for a successful connection. If the test fails, the minorErrorCode() is used when writing the secondary error to the page.

Listing 9.74 Using minorErrorCode() to Retrieve a Secondary Database Connection Error

<server>

// Open a connection.
var myConn = database.connect("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

if (myConn.connected()) {
    // You are connected, so perform any tasks here.

}else{

    // There was an error connecting to the database.
    write('Error ('+myConn.minorErrorCode()+'): '+myConn.minorErrorMessage);
}

</server>

database.minorErrorMessage()

ES2+

 

Syntax

database.minorErrorMessage()

Description

The minorErrorMessage() method of the database object contains the secondary ODBC or database string error message that is returned if an error occurs.

Example

Listing 9.75 shows how you would create a connection and test for a successful connection. If the test fails, the minorErrorMessage() is used when writing the secondary error to the page.

Listing 9.75 Using minorErrorMessage() to Retrieve a Secondary Database Connection Error

<server>

// Open a connection.
var myConn = database.connect("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

if (myConn.connected()) {

    // You are connected, so perform any tasks here.

}else{

    // There was an error connecting to the database.
    write('Error ('+myConn.minorErrorCode()+'): '+myConn.minorErrorMessage);
}

</server>

database.prototype

ES2+

 

Syntax

database.prototype.method = name

database.prototype.property = value

Description

The prototype property of the database object allows you to add methods and properties to the database object. If you are adding a method, you set the instance equal to the name of the method you have defined.

Example

Listing 9.76 creates a new property and method of the database object. An instance is created and the new property is set. The new method is then called to verify the property, and, if it is incorrect (which it is), an error message is written to the page.

Listing 9.76 Using the prototype Property to Create a New Property and Method

<server>

// Define the method that we prototyped.
function verifyODBC(){

    // Check to see if the type property we added is set to a valid value.
    if(this.type == "ODBC"){
       return true;
    }else{
       return false;
    }
}

// Create a new property and method of the database object.
database.prototype.type = null;
database.prototype.isODBC = verifyODBC;

// Open a connection.
var myConn = database.connect("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Using the prototype we defined, assign the type property.
myConn.type = "Oracle";

// Check the type of the connection to see if it is valid.
if(myConn.isODBC()){
    write(myConn + " has a valid type of " + myConn.type);
}else{
    write(myConn + " has an invalid type of " + myConn.type);
}

</server>

database.rollbackTransaction()

ES2+

 

Syntax

database.rollbackTransaction()

Description

The rollbackTransaction() method of the database object will undo all actions performed since the last beginTransaction() method call.

Example

Listing 9.77 takes a commit field sent to the application from the user. If this evaluates to true, the transaction is committed. If not, it is rolled back.

Listing 9.77 Rolling Back a Transaction with the rollbackTransaction() Method

<server>

// See if the user wants to commit the last transaction.
client.commit = request.commit;

if(client.commit = "YES"){

    // Commit the transaction.
    myConn.commitTransaction();

}else{

    // Rollback the transaction.
    myConn.rollbackTransaction();
}

</server>

database.SQLTable()

ES2+

 

Syntax

database.SQLTable(sql)

Description

The SQLTable() method of the database object takes a sql SELECT statement as a parameter and executes this query through the connection from which it was called. It returns the results formatted in an HTML table for easy writing to a client’s page. This is a simple table in the following format:

<table border="1">
<tr>
<th>column 1 </th>
<th>column 2 </th>

<th>column N </th>
</tr>
<tr>
<td>value 1 of column 1 </td>
<td>value 1 of column 2 </td>

<td>value 1 of column N </td>
</tr>
<tr>
<td>value 2 of column 1 </td>
<td>value 2 of column 2 </td>

<td>value 2 of column N </td>
</tr>

</table>

Example

Listing 9.78 runs a user passed query and formats the result using the SQLTable() method. This information is then written to the user’s page.

Listing 9.78 Using the SQLTable() Method to Format the Result of a SELECT Query

<server>

// Assign the user submitted query to the client object.
client.sql = request.sql;

// Open a connection.
var myConn = database.connect("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

if(myConn.connected()){

  // Start a new transaction and write the results to a page, formatting
  // them with the SQLTable method.
  myConn.beginTransaction();
  write(myConn.SQLTable(client.sql));

  // Commit the transaction.
  myConn.commitTransaction();

// If the connection fails, write an error message.
}else{
  write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

// Release the connection.
myConn.release();

</server>

database.storedProc()

ES3+

 

Syntax

database.storedProc(procName)

database.storedProc(procName, arg1, arg2, …, argN)

Description

The storedProc() method of the database object creates a Stproc object that allows you to execute a database-specific stored procedure using the connection from which it was invoked.

As shown in the syntactical definition, you can also pass any arguments needed to the method for processing. If you are using a stored procedure that requires arguments, or if you want to have the procedure run using default arguments, you must pass /Default/ as the argument. The following shows an example of passing a default value:

var myStproc = myConn.storedProc("sp_employees", "/Default/");

The scope of this procedure is restricted to the current page. Any methods of the Stproc object must be invoked on the current page. If this is not possible, a new object will have to be created on subsequent pages to access the properties needed.

Example

Listing 9.79 creates a connection to a database. When the connection has been verified, the storedProc() method is used to invoke the fictitious sp_employees stored procedure.

Listing 9.79 Using the storedProc() Method to Invoke a Stored Procedure on a Database

<server>

// Open a connection.
var myConn = database.connect("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

if(myConn.connected()){

  myConn.beginTransaction();

  // Run the stored procedure.
  var myStproc = myConn.storedProc("sp_employees");

  // Commit the transaction.
  myConn.commitTransaction();

// If the connection fails, write an error message.
}else{
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

// Release the connection.
myConn.release();

</server> >

database.storedProcArgs()

ES3+

 

Syntax

database.storedProcArgs(procName)

database.storedProcArgs(procName, type1, type2, …, typeN)

Description

The storedProcArgs() method of the database object creates a Stproc object that allows you to execute a database-specific stored procedure using the connection from which it was invoked on DB2, ODBC, and Sybase databases. If this method is invoked on Informix or Oracle databases, it has no effect. The difference between this method and the storedProc() method is that this method takes a type as a parameter for the arguments passed. These types can be IN, OUT, or INOUT. The following shows an example of passing these types:

var myStproc = myConn.storedProc("sp_employees", "INOUT", "OUT");

The scope of this procedure is restricted to the current page. Any methods of the Stproc object must be invoked on the current page. If this is not possible, a new object will have to be created on subsequent pages to access the properties needed.

Example

Listing 9.80 creates a connection to a database. After the connection has been verified, the storedProc() method is used to invoke the fictitious sp_employees stored procedure, and the storedProcArgs() method is used to specify the argument types.

Listing 9.80 Using the storedProcArgs() Method to Set the Argument Types of a Stored Procedure

<server>

// Open a connection.
var myConn = database.connect("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

if(myConn.connected()){

    myConn.beginTransaction();

    // Run the stored procedure.
    var myStprocArgs = myConn.storedProcArgs("sp_employees", "IN", "INOUT");
    var myStproc = myConn.storedProc("sp_employees", 3, "%John%");

    // Commit the transaction.
    myConn.commitTransaction();

// If the connection fails, write an error message.
}else{
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

// Release the connection.
myConn.release();

</server>

database.toString()

ES2+

 

Syntax

database.toString()

Description

The toString() method of the database object returns a text value of the object. When invoked on an instance of a database object, the string is returned in the following format:

"dbName" "uid" "dbType" "dbInstance"

If the parameter is unknown, an empty string is returned. Table 9.10 contains the value of these returned values.

Table 9.10 Return Values of the toString() Method

Image

Example

Listing 9.81 creates an instance of the database object. Once created, the write() method is used to write its string value to the page.

Listing 9.81 Write the Results of Calling the toString() Method to a Page

<server>

// Open a connection.
var myConn = database.connect("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

if(myConn.connected()){

    // Write the string value of the object to the page.
    write(myConn.toString());

// If the connection fails, write an error message.
}else{
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}


// Release the connection.
myConn.release();

</server>

database.unwatch()

ES3+

 

Syntax

database.unwatch(property)

Description

The unwatch() method of the database object is used to turn off the watch for a particular property.

Example

Listing 9.82 shows how the unwatch() method is used to stop watching the user-defined property p.

Listing 9.82 Example of the unwatch() Method

<server>

// Define the method that we prototyped.
function verifyODBC(){

    // Check to see if the type property we added is set to a valid value.
    if(this.type == "ODBC"){
       return true;
    }else{
       return false;
    }
}

// function that is called if property's value changes
function alertme(id, oldValue, newValue){
    write("ID (" + id + ") changed from " + oldValue + " to " + newValue);
    return newValue;
}

// Create a new property and method of the database object.
database.prototype.type = null;
database.prototype.isODBC = verifyODBC;

// Open a connection.
var myConn = database.connect("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");
// Using the prototype we defined, assign the type property.
myConn.type = "Oracle";

// Check the type of the connection to see if it is valid.
if(myConn.isODBC()){
    write(myConn + " has a valid type of " + myConn.type);
}else{
    write(myConn + " has an invalid type of " + myConn.type);
}

// watch property
myConn.watch("type", alertme);

// change value
myConn.type = null;

// turn off watch
myConn.unwatch("type");

// change value again
myConn.type = "Sybase";

</server>

database.watch()

ES3+

 

Syntax

database.watch(property, function)

Description

The watch() method of the database object is used to turn on the watch for a particular property specified by property. Any time the specified property is changed after the watch() method has been called, the specified function is called.

Example

Listing 9.83 shows how the watch() method is used to start watching the user-defined property p.

Listing 9.83 Example of the watch() Method

<server>




// Define the method that we prototyped.

function verifyODBC(){

    // Check to see if the type property we added is set to a valid value.
    if(this.type == "ODBC"){
       return true;
    }else{
       return false;
    }
}

// function that is called if property's value changes
function alertme(id, oldValue, newValue){
    write("ID (" + id + ") changed from " + oldValue + " to " + newValue);
    return newValue;
}

// Create a new property and method of the database object.
database.prototype.type = null;
database.prototype.isODBC = verifyODBC;

// Open a connection.
var myConn = database.connect("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Using the prototype we defined, assign the type property.
myConn.type = "Oracle";

// Check the type of the connection to see if it is valid.
if(myConn.isODBC()){
    write(myConn + " has a valid type of " + myConn.type);
}else{
    write(myConn + " has an invalid type of " + myConn.type);
}

// watch property
myConn.watch("type", alertme);

// change value
myConn.type = null;



</server>

DbPool

ES3+

Syntax

new DbPool()

new DbPool(dbTypedbInstanceuidpwddbName)

new DbPool(dbTypedbInstanceuidpwddbNamemaxConn)
new DbPool(dbTypedbInstanceuidpwddbNamemaxConncommitFlag)

Description

The DbPool object is an object that holds a “pool” of connections to a database. Before you open a connection to a database and have the ability to run queries against it, you should create an instance of this object. After the instance is created, connections can be obtained from the pool as needed. The pool object itself takes all the parameters necessary to make the connection. It is possible to create a pool without specifying any parameters; however, you must pass the parameters when the first connection is attempted.

The creation of a DbPool object is done using the format defined in the syntax definition. Each parameter is defined in Table 9.11.

Table 9.11 Parameters of the DbPool Object

Image

Depending on your database, it is possible to create an instance of this object by passing a limited set of these parameters, as well as passing none. The object itself has the methods listed in Table 9.12.

Table 9.12 Methods of the DbPool Object

Image

Example

Listing 9.84 creates a pool of connections to an Oracle database and initializes a connection from that pool. It takes a user’s UID and name that was passed in, runs a query (based on the UID) against the database to find that user’s information, and updates her name. If a connection is not made, the error code and message are returned to the screen.

Listing 9.84 Creating and Using a DbPool Object

<server>

// Assign the user submitted ID and name to the client object as properties.
client.uid = request.uid;
client.name = request.name;

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Open a connection from the pool. Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);
if(myConn){
    // Start a new SQL transaction to perform a SELECT.
    myConn.beginTransaction();
    var currRow = myConn.cursor('SELECT * FROM employees WHERE uid = '
  + client.uid);
    // Focus on that line, change the name column for that user,
    // and update the row.
    currRow.next();
    currRow.name = client.name;
    currRow.updateRow("employees");

    // Close the cursor.
    currRow.close();

// If the connection fails, write an error message.
}else{
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

</server>

DbPool.connect()

ES3+

Syntax

dbpool.connect(dbType, dbInstance, uid, pwd, dbName)

dbpool.connect(dbType, dbInstance, uid, pwd, dbName, maxConn)

dbpool.connect(dbType, dbInstance, uid, pwd, dbName, maxConn, commitFlag)

Description

The connect method of the DbPool object is used to connect to a database when the connection was not made with the initialization of the original DbPool object. The method takes all the parameters necessary to connect to the database. Each parameter is defined in Table 9.9.

Table 9.13 Parameters of the connect() Method

Image

Depending on your database, it is possible to create an instance of this object by passing a limited set of these parameters. See your database documentation for this information.

Example

Listing 9.85 creates a connection pool. The connect() method is then called to open the pool to an Oracle database. If a connection is not made, the error code and message are returned to the screen.

Listing 9.85 Connecting to a Database Using the connect() Method

<server>
 // Assign the user submitted ID and name to the client object as properties. client.uid = request.uid; client.name = request.name;  // Create a pool of connections. var myPool = new DbPool();  // Create a connection for the pool. myPool.connect("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");  // Open a connection from the pool. Give error if connection could // not be made. var myConn = myPool.connection('Employees', 15);  if(myConn.connected()){      // Do any database stuff here.
// If the connection fails, write an error message.
}else{
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

</server>

DbPool.connected()

ES3+

Syntax

dbpool.connected()

Description

The connected() method of the DbPool object tells whether the pool of connections to the database is still connected.

Example

Listing 9.86 creates a pool of connections and pulls a connection from the pool for processing. If the connection is made, any code within that section is executed. If the connection fails, the error is written to the page.

Listing 9.86 Testing a Connection with the connected() Method

<server>

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Open a connection from the pool. Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);

if (myConn.connected()) {

    // You are connected, so perform any tasks here.

}else{

    // There was an error connecting to the database.
    write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}

</server>

DbPool.connection()

ES3+

Syntax

dbpool.connection(name, seconds);

Description

The connection() method of the DbPool object pulls a connection from the pool. The connection is returned from the method and can be stored in a variable to be used for processing.

The method takes two parameters. The first parameter is a name, which is a name you can give your connection. Because you actually store the connection in a variable, this name’s primary function becomes one for debugging purposes. The second parameter is a seconds value for the number of seconds you give the instance to connect.

Example

Listing 9.87 creates a pool of connections to an Oracle database and initializes a connection from that pool. It takes a user’s UID and name that was passed in, runs a query (based on the UID) against the database to find that user’s information, and updates her name. If a connection is not made, the error code and message are returned to the screen.

Listing 9.87 Creating and Using a connection() Method

<server>
 // Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");
 // Open a connection from the pool. Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);
 if (myConn.connected()) {
 // You are connected, so perform any tasks here.
 }else{
 // There was an error connecting to the database.
write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}
 
</server>

DbPool.DbPool()

ES3+

 

Syntax

new DbPool()

new DbPool(dbType, dbInstance, uid, pwd, dbName)

new DbPool(dbType, dbInstance, uid, pwd, dbName, maxConn)

new DbPool(dbType, dbInstance, uid, pwd, dbName, maxConn, commitFlag)

Description

The DbPool() method of the DbPool object is the underlying method that creates a “pool” of connections to a database. The creation of a DbPool object is done using the format defined in the syntax definition. Each parameter is defined in Table 9.14.

Table 9.14 Parameters of the DbPool() Method

Image

Depending on your database, it is possible to create an instance of this object by passing a limited set of these parameters.

Example

Listing 9.88 creates a pool of connections and pulls a connection from the pool for processing. If the connection is made, any code within that section is executed. If the connection fails, the error is written to the page.

Listing 9.88 The DbPool() Method is the Underlying Method Used When a DbPool Object Instance Is Created

<server>
 // Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");
 
// Open a connection from the pool. Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);
 if (myConn.connected()) {
 // You are connected, so perform any tasks here.
 }else{
 // There was an error connecting to the database.
write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}
 </server>

DbPool.disconnect()

ES3+

 

Syntax

dbpool.disconnect()

Description

The disconnect() method of the DbPool object disconnects all connections to a database within that pool.

Example

Listing 9.89 creates a connection to an Oracle database. The next line drops the connection by using the disconnect() method.

Listing 9.89 Disconnecting from a Database Using the disconnect() Method

<server>
 // Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");
// Drop the connections.
myPool.disconnect();
 </server>

DbPool.majorErrorCode()

ES3+

 

Syntax

dbpool.majorErrorCode()

Description

The majorErrorCode() method of the DbPool object contains the ODBC or database numeric error code that is returned if an error occurs.

Example

Listing 9.90 shows how you would create a pool of connections and test for the connection. If the test fails, the majorErrorCode() is used when writing the error to the page.

Listing 9.90 Using majorErrorCode() to Retrieve a Database Connection Error

<server>
 // Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");
 if (myPool.connected()) {
 // You are connected, so perform any tasks here.
 }else{
 // There was an error connecting to the database.
write('Error ('+myPool.majorErrorCode()+'): '+myPool.majorErrorMessage);
}
 </server>

DbPool.majorErrorMessage()

ES3+

 

Syntax

dbpool.majorErrorMessage()

Description

The majorErrorMessage() method of the DbPool object contains the ODBC or database string error message that is returned if an error occurs.

Example

Listing 9.91 shows how you would create a pool of connections and test for the connection. If the test fails, the majorErrorMessage() method is used to write the error to the page.

Listing 9.91 Using majorErrorMessage() to Retrieve a Database Connection Error

<server> // Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");
 if (myPool.connected()) {
 // You are connected, so perform any tasks here.
 }else{
 // There was an error connecting to the database.
write('Error ('+myPool.majorErrorCode()+'): '+myPool.majorErrorMessage);

}

</server>

DbPool.minorErrorCode()

ES3+

 

Syntax

dbpool.minorErrorCode()

Description

The minorErrorCode() method of the DbPool object contains the secondary ODBC or database numeric error code that is returned if an error occurs.

Example

Listing 9.92 shows how to create a pool of connections and test for the connection. If the test fails, the minorErrorCode() method is used to write the secondary error to the page.

Listing 9.92 Using minorErrorCode() to Retrieve a Secondary Database Connection Error

<server>
 // Create a pool of connections.
 var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");
 if (myPool.connected()) {
 // You are connected, so perform any tasks here.
 }else{
 // There was an error connecting to the database.
write('Error ('+myPool.minorErrorCode()+'): '+myPool.minorErrorMessage);

}
 
</server>

DbPool.minorErrorMessage()

ES3+

 

Syntax

dbpool.minorErrorMessage()

Description

The minorErrorMessage() method of the DbPool object contains the secondary ODBC or database string error message that is returned if an error occurs.

Example

Listing 9.93 shows how to create a pool of connections and test for the connection. If the test fails, the minorErrorMessage() method is used to write the secondary error to the page.

Listing 9.93 Using minorErrorMessage() to Retrieve a Secondary Database Connection Error

<server>
 // Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");
 if (myPool.connected()) {
 // You are connected, so perform any tasks here.
 }else{
 // There was an error connecting to the database.
write('Error ('+myPool.minorErrorCode()+'): '+myPool.minorErrorMessage);
}

</server>

DbPool.prototype

ES3+

 

Syntax

dbpool.prototype.method = name dbpool.prototype.property = value

Description

The prototype property of the DbPool object allows you to add methods and properties to the DbPool object. If you are adding a method, you set the instance equal to the name of the method you have defined.

Example

Listing 9.94 creates a new property and method of the DbPool object. An instance is created and the new property is set. The new method is then called to verify the property, and, if it is incorrect, an error message is written to the page.

Listing 9.94 Using the prototype Property to Create a New Property and Method

<server>
 // Define the method that we prototyped.
function verifyOracle(){
 // Check to see if the type property we added is set to a valid value.
if(this.type == "Oracle"){
return true;
}else{
return false;
}
}
 // Create a new property and method of the DbPool object.
DbPool.prototype.type = null;
DbPool.prototype.isOracle = verifyOracle;
 // Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Using the prototype we defined, assign the type property.
myPool.type = "Oracle";
 // Check the type of the connection to see if it is valid.
if(myPool.isOracle()){
write(myPool + " has a valid type of " + myPool.type);
}else{
write(myPool + " has an invalid type of " + myPool.type);
}

</server>

DbPool.storedProcArgs()

ES3+

 

Syntax

database.storedProcArgs(procName) database.storedProcArgs(procName, type1, type2, …, typeN)

Description

The storedProcArgs() method of the database object creates a Stproc object that allows you to execute a database-specific stored procedure using the connection from which it was invoked on DB2, ODBC, and Sybase databases. If this method is invoked on Informix or Oracle databases, it has no affect. The difference between this method and the storedProc() method is that this method takes a type as a parameter for the arguments passed. These types can be IN, OUT, or INOUT. The following shows an example of passing these types:

var myStproc = myConn.storedProc("sp_employees", "INOUT", "OUT");

The scope of this procedure is restricted to the current page. Any methods of the Stproc object must be invoked on the current page. If this is not possible, a new object will have to be created on subsequent pages to access the properties needed.

Example

Listing 9.95 creates a pool of connections to a database. The storedProc() method is used to invoke the fictitious sp_employees stored procedure, and the storedProcArgs() method is used to specify the argument types.

Listing 9.95 Using the storedProcArgs() Method to Set the Argument Types of a Stored Procedure

<server>
 // Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Set the stored procedure arguments.
var myStprocArgs = myPool.storedProcArgs("sp_employees", "IN", "INOUT");
var myStproc = myPool.storedProc("sp_employees", 3, "%John%");
 </server>

DbPool.toString()

ES3+

Syntax

dbpool.toString()

Description

The toString() method of the DbPool object returns a text value of the object. When invoked on an instance of a DbPool object, the string is returned in the following format:

"dbName" "uid" "dbType" "dbInstance"

If the parameter is unknown, an empty string is returned. Table 9.15 contains the value of these returned values.

Table 9.15 Return Values of the toString() Method

Image

Example

Listing 9.96 creates an instance of the DbPool object. Once created, the write()

Listing 9.96 Write the Results of Calling the toString() Method to a Page

<server>
 // Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");
 // Open a connection from the pool. Give error if connection could
// not be made.
var myConn = myPool.connection('Employees', 15);
if(myConn.connected()){
 // Write the string value of the object to the page.
write(myPool.toString());
 // If the connection fails, write an error message.
}else{
write('Error ('+myConn.majorErrorCode()+'): '' + myConn.majorErrorMessage();
}
 // Release the connection.
myConn.release();
</server>

DBPool.unwatch()

ES3+

Syntax

dbpool.unwatch(property)

Description

The unwatch() method of the DbPool object is used to turn off the watch for a particular property.

Example

Listing 9.97 shows how the unwatch() method is used to stop watching the user-defined property p.

Listing 9.97 Example of the unwatch() Method

<server>
// Define the method that we prototyped.
function verifyOracle(){
 // Check to see if the type property we added is set to a valid value.
if(this.type == "Oracle"){
return true;
}else{
return false;
}
}
 // function that is called if property's value changes
function alertme(id, oldValue, newValue){
write("ID (" + id + ") changed from " + oldValue + " to " + newValue);
return newValue;
}
 // Create a new property and method of the DbPool object.
DbPool.prototype.type = null;
DbPool.prototype.isOracle = verifyOracle;
 // Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");
 // Using the prototype we defined, assign the type property.

myPool.type = "Oracle";
 // watch property
myPool.watch("type", alertme);
 // Check the type of the connection to see if it is valid.
if(myPool.isOracle()){
write(myPool + " has a valid type of " + myPool.type);
}else{

write(myPool + " has an invalid type of " + myPool.type);
}
 // change value
myPool.type = null;
 // turn off watch
myPool.unwatch("type");
 // change value again
myPool.type = "Sybase";
 </server>

DBPool.watch()

ES3+

 

Syntax

dbpool.watch(property, function)

Description

The watch() method of the DBPool object is used to turn on the watch for a particular property specified by property. Any time the specified property is changed after the watch() method has been called, the specified function is called.

Example

Listing 9.98 shows how the watch() method is used to start watching the user-defined property p.

Listing 9.98 Example of the watch() Method

<server>

// Define the method that we prototyped.
function verifyOracle(){

   // Check to see if the type property we added is set to a valid value.
   if(this.type == "Oracle"){
        return true;
     }else{
        return false;
    }
 }
// function that is called if property's value changes
 function alertme(id, oldValue, newValue){
     write("ID (" + id + ") changed from " + oldValue + " to " + newValue);
     return newValue;
}

// Create a new property and method of the DbPool object.
DbPool.prototype.type = null;
DbPool.prototype.isOracle = verifyOracle;

// Create a pool of connections.
var myPool = new DbPool("ORACLE", "mySID", "myApp", "appsPWD", "myTNS");

// Using the prototype we defined, assign the type property.
myPool.type = "Oracle";

// watch property
myPool.watch("type", alertme);

// Check the type of the connection to see if it is valid.
if(myPool.isOracle()){
  write(myPool + " has a valid type of " + myPool.type);
}else{
  write(myPool + " has an invalid type of " + myPool.type);
}
// change value
myPool.type = null;

</server>

debug()

ES2+

 

Syntax

debug(expression)
debug(variable)

Description

The debug function is a top-level function that is not associated with any core object. This function is used to display the value of an expression or variable in the Trace Information window when running the application in the JavaScript Application Manager’s debug window.

Example

Listing 9.99, when run in the JavaScript Application Manager’s debugger, will display the value of the request.name when encountered.

Listing 9.99 Using the debug() Function to Write Information to the Trace Information Window

<server>

// Display the value of the name passed in the request
// to the application.
debug(request.name);

</server>

deleteResponseHeader()

ES3+

 

Syntax

deleteResponseHeader(key)

Description

The deleteResponseHeader() function is a top-level function and is not associated with any core object. This function is used to delete fields in the HTTP header before it is sent back to the client. Because of when the actual header is sent in relation to the body of the data, you should be sure to delete these fields before you call the flush() or redirect() functions.

Example

Listing 9.100 shows how you can delete the content-type header field before it is sent back to the browser.

Listing 9.100 Using the deleteResponseHeader() Function to Delete the content.type of a File Being Sent to a Browser

<server>

// Delete a field to the header.
deleteResponseHeader("content-type");

</server>

File()

ES2+

 

Syntax

new File(path)

Description

The File object allows you to perform various tasks such as reading and writing to a file on your disk. The object itself has many methods to use and a prototype property that allows a programmer to create new properties and methods of the object. Table 9.16 lists the methods accessible and a brief description of each. An instance of this object is created by simply passing the path of the file you want to create or read.

Table 9.16 Methods of the File Object

Image

The usage of the File object is very straightforward. The methods provided allow you to perform the various tasks needed on the files on your file system. Part of this functionality of working with these files is to allow programmers to specify how they want to open the files. A file can be opened to read, write, append, or open in binary mode. These options are specified in the open() method in the following form:

myFile.open("option");

Table 9.17 gives a list and description of these options.

Table 9.17 Options of the open() Method

Image

Example

Listing 9.101 displays an option menu that allows a user to select a file to read. When the form is submitted, the script reads the file and displays its contents on a page.

Listing 9.101 Using the File Object

<html>
<head>
  <title> Using the File object</title>
</head>
<body>
<server>

// See if they have submitted or just need the forml
if(request.method == "POST"){

    // Create an instance of the File object and pass it the file
    // the user specified they wanted to view.
    var myLog = new File(request.file);

    // Try to open the file.
    if(!myLog.open("r")){

       // If there was an error, tell the user.
       write("There was an error opening the file: " + request.file);
    }else{

    // If there was not an error, then open the file and display it.
    write('<h3>The contents of ' + request.file + ' are as follows:</h3>'),
    while(!myLog.eof()){
    write(myLog.readln());
    }
   }
  }else{
    // If this page was called then write the select box to the page for
    // the user to use to select which log they want to see.


    write('<form name="myForm" method="post">'),
    write('<select name="file">'),
    write('<option value="/logs/admin.log">Admin Log</option>'),
    write('<option value="/logs/user.log">User Log</option>'),
    write('<option value="/logs/error.log">Error Log</option>'),
    write('</select>'),
    write('<input type="submit" value="View Log">'),
    write('</form>'),
}

</server>
</body>
</html>

File.byteToString()

ES2+

Syntax

File.byteToString(num)

Description

The byteToString() method of the File object is used to convert the numeric value passed to its ASCII equivalent. If the method is not passed a number, an empty string is returned.

Example

Listing 9.102 opens two files, one for reading and the other for appending. Bytes are then read using the readByte() method from the first file, converted back to string characters using the byteToString() method, and written to the second file. Both files are closed when the process has completed.

Listing 9.102 Using the byteToString() Method to Convert the Bytes Read into Strings

<server>

// Open a log file and a summary file.
var myLog = new File("/data/logs/today.log");
var mySummary = new File("/data/logs/summary.log");

// Open the log file for reading and the summary file for
// appending.
myLog.open("r");

mySummary.open("a");

// Append the contents of the log file to the summary file.
while (!myLog.eof()){
    myBytes = File.byteToString(myLog.readByte());
    mySummary.write(myBytes);
}

// Close the files.
myLog.close();
mySummary.close();

</server>

File.clearError()

ES2+

Syntax

file.clearError()

Description

The clearError() method of the File object clears the file error status and the value returned by the eof() method.

Example

Listing 9.103 opens a file for reading. If the operation returned an error, the error is written to the page. If there was an error, it is cleared after writing it.

Listing 9.103 Using the clearError() Method to Clear File Errors

<server>

 // Open a log file.
var myLog = new File("/data/logs/today.log");

// Open the log file for reading.
myLog.open("r");

if (myLog.error() == 0) {

   // Perform actions on file.

}else{

    // Write out the error.
  write('Error: ' + myLog.error());

    // Clear the error.
    myLog.clearError()
}
// Close the file.
myLog.close();

</server>
</body>
</html>

File.close()

ES2+

Syntax

file.close()

Description

The close() method of the File object closes the file on which it has been invoked. This method returns true if it was successful and false if it was unsuccessful.

Example

Listing 9.104 shows how to open a file and then close it.

Listing 9.104 Closing a File with the close() Method

<server>

// Open a log file.
var myLog = new File("/data/logs/today.log");

// Open the log file for reading.
myLog.open("r");

// Close the file.
myLog.close();

</server>

File.constructor

ES2+

 

Syntax

file.constructor

Description

The constructor property of the File object specifies the function that creates the object.

Example

Listing 9.2105 shows an example of the constructor property.

Listing 9.105 Example of the constructor Property

<server>

// Open a log file.
var myLog = new File("/data/logs/today.log");

// Open the log file for reading.
myLog.open("r");

if(myLog.constructor == File){
       write("Object created");
}


// Close the file.
myLog.close();

</server>

File.eof()

ES2+

Syntax

file.eof()

Description

The eof() method of the File object returns true if the position of the pointer within the file is past the end of the file. It returns false otherwise.

Example

Listing 9.106 reads a file and writes its contents to the page until the end of the file is found with the eof() method.

Listing 9.106 Reading a File Until You Come to the End of It, Which Can Be Evaluated Using the eof() Method

<server>
// Open a log file for reading.
var myLog = new File("/data/logs/today.log");
myLog.open("r");

// Write the contents of the log file to the page.
while (!myLog.eof()){
    myBytes = File.byteToString(myLog.readByte());
    write(myBytes);
}

// Close the file.
myLog.close();

</server>

File.error()

ES2+

 

Syntax

file.error()

Description

The error() method of the File object returns the operating system error code when an error occurs opening a file. This method returns 0 if there is no error, and –1 if the file you invoke the method on is unable to be opened.

Example

Listing 9.107 opens a file for reading. If there was a problem during this operation, the error is written to the user’s page.

Listing 9.107 Using the error() Method to Access an Error to Write to the User’s Page

<server>
// Open a log file.
var myLog = new File("/data/logs/today.log");

// Open the log file for reading.
myLog.open("r");
if (myLog.error() == 0) {

  // Perform actions on file.

}else{

  // Write out the error.
  write('Error: ' + myLog.error());

  // Clear the error.
  myLog.clearError()
}

// Close the file.
myLog.close();

</server>

File.exists()

ES2+

 

Syntax

file.exists()

Description

The exists() method of the File object returns a boolean value based on the existence of the file in which it was invoked. If the file exists, the method returns true. It returns false if the file does not exist.

Example

Listing 9.108 opens a file and then checks to see whether it exists.

Listing 9.108 Using the exists() Method to See Whether a File Exists

<server>

// Open a log file.
var myLog = new File("/data/logs/today.log");

// See if the file exists.
if(myLog.exists()){
    write('The file exists'),
}else{
    write('The file does not exist'),
}

</server>

File.flush()

ES2+

 

Syntax

file.flush()

Description

The flush() method of the File object is used to write buffered information to a file. This information is placed in a buffer when the write(), writeln(), and writeByte() methods are used. Note that this is not the same as the top-level flush function.

Example

Listing 9.109 opens a file for reading and another file for writing. If the file for reading exists, a string is written to the other file. The flush() method is used to write the buffered information to the file.

Listing 9.109 Using the flush() Method

<server>
// Open a log file.
var myLog = new File("/data/logs/today.log");
var mySummary = new File("/data/logs/summary.log");

myLog.open("r");
mySummary.open("w");

// See if the file exists.
if(myLog.exists()){
    mySummary.write('The file exists'),
}else{
    mySummary.write('The file does not exist'),
}

// Write the data in the buffer to the file.
mySummary.flush();

// Close the file.
myLog.close();
mySummary.close();

</server>

File.getLength()

ES2+

 

Syntax

file.getLength()

Description

The getLength() method of the File object returns the number of characters in a text file or the number of bytes in a binary file. If the method is unsuccessful, –1 is returned.

Example

Listing 9.110 opens a file for reading and another file for writing. The getLength() method is used in a for loop to determine when to stop reading from the file.

Listing 9.110 Using the getLength() Method

<server> // Open the files.
var myLog = new File("/data/logs/today.log");
var mySummary = new File("/data/logs/summary.log");
myLog.open("r");
mySummary.open("w");

// Write the contents of the log file to the page.
for(var i = 0; i <= myLog.getLength(); i++){
    myBytes = File.byteToString(myLog.readByte());
    mySummary.write(myBytes);
}

mySummary.flush();

// Close the files.
myLog.close();
mySummary.close();

</server>

File.getPosition()

ES2+

 

Syntax

file.getPosition()

Description

The getPosition() method of the File object returns the zero-based index position of the current pointer in the file. If the pointer is on the first character, 0 is returned. If there is an error, -1 is returned.

Example

Listing 9.111 loops through each character, printing it on a new line next to its indexed location.

Listing 9.111 Using the getPosition() Method

<server>

// Open the files.
var myLog = new File("/data/logs/today.log");
var mySummary = new File("/data/logs/summary.log");
myLog.open("r");
mySummary.open("w");

// Write the contents of the log file to the page.
for(var i = 0; i <= myLog.getLength(); i++){
    myBytes = File.byteToString(myLog.readByte());
    mySummary.write('Character '+mySummary.getPosition()+' is '+myBytes+'<br>'),
}

mySummary.flush();

// Close the files.
myLog.close();
mySummary.close();

</server>

File.open()

ES2+

 

Syntax

file.open(option)

Description

The open() method of the File object is used to open a file to read, write, and/or append to. The method returns true if it is successful and false otherwise. The options passed determine the mode in which the file is opened. The options are specified in Table 9.18.

Table 9.18 Options of the open() Method

Image

Example

Listing 9.112 shows how to open a file in read mode.

Listing 9.112 Using the open() Method to Open a File

<server>
// Initialize a file
var myLog = new File("/data/logs/today.log");

// Open the file in read mode
myLog.open("r");

// Close the file
myLog.close();

</server>

File.prototype

ES3+

 

Syntax

file.prototype.method = name
file.prototype.property = value

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.100.89