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.
ES2+
addClient(URL)
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.
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.
<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.
<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>
ES3+
addResponseHeader(key, value)
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.
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.
<server>
// Add a field to the header
addResponseHeader("content-type", "application/x-javascript");
</server>
ASP1+
Core ASP environment object
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.
Listing 9.4 shows how you could specify the version of your application that users are implementing, and then write it out.
<script runat="server" type="text/jscript" language="JScript">
Application("version") = "1.0"
var appVer = Application("version");
Response.Write(appVer);
</script>
ASP1+
function Application_OnEnd(){
code
}
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.
Listing 9.5 shows how you can append a string to the end of the log file of the last request of an application.
<script runat="server" type="text/jscript" language="JScript">
function Application_OnEnd(){
Response.AppendToLog("Your application has ended");
}
</script>
ASP1+
function Application_OnStart(){
code
}
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.
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.
<script runat="server" type="text/jscript" language="JScript">
function Application_OnStart(){
Response.AppendToLog("Your application has started");
}
</script>
ASP1+
Application.Contents(name)
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.
Listing 9.7 shows how you can use the Remove()
method of the Contents
collection to remove myItem, which was added to the application.
<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>
ASP1+
Application.Contents.Remove(name)
Application.Contents.Remove(num)
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.
Listing 9.8 shows how you can use the Remove()
method of the Contents
collection to remove myItem, which was added to the application.
<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>
ASP1+
Application.Contents.RemoveAll()
The RemoveAll()
method of the Contents
collection of the Application
object is used to remove all items from the application’s collection.
Listing 9.9 shows how you can use the RemoveAll()
method of the Contents
collection to remove all items that have been added to the application.
<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>
ASP1+
Application.Lock()
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.
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.
<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>
ASP1+
Application.StaticObjects(name)
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.
Listing 9.11 shows how you can grab the instance myControl from your current ASP page.
<script runat="server" type="text/jscript" language="JScript">
Application.StaticObjects("myControl");
</script>
ASP1+
Application.Unlock()
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.
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.
<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>
ASP3+
Core ASP environment object
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.
Listing 9.13 shows how you can write out a short description of an error that has been exposed to the ASPError
object.
<script runat="server" type="text/jscript" language="JScript">
Response.Write(ASPError.Description);
</script>
ASP3+
ASPError.ASPCode
The ASPCode
property of the ASPError
object contains error code generated by IIS.
In Listing 9.14 we write out the value of the ASPCode
property.
<script runat="server" type="text/jscript" language="JScript">
Response.Write(ASPError.ASPCode);
</script>
ASP3+
ASPError.ASPDescription
The ASPDescription
property of the ASPError
object contains a more detailed description of the error returned.
In Listing 9.15 we write out the value of the ASPDescription
property.
<script runat="server" type="text/jscript" language="JScript">
Response.Write(ASPError.ASPDescription);
</script>
ASP3+
ASPError.Category
The Category
property of the ASPError
object indicates if the source of the error was internal to ASP, JScript, or an object.
In Listing 9.16 we write out the value of the Category
property.
<script runat="server" type="text/jscript" language="JScript">
Response.Write(ASPError.Category);
</script>
ASP3+
ASPError.Column
The Column
property of the ASPError
object contains the column position within the ASP file where the error occurred.
In Listing 9.17 we write out the value of the Column
property.
<script runat="server" type="text/jscript" language="JScript">
Response.Write(ASPError.Column);
</script>
ASP3+
ASPError.Description
The Description
property of the ASPError
object contains a short description of the error.
In Listing 9.18 we write out the value of the Description
property.
<script runat="server" type="text/jscript" language="JScript">
Response.Write(ASPError.Description);
</script>
ASP3+
ASPError.File
The File
property of the ASPError
object contains the name of the ASP file being processed when the error occurred.
In Listing 9.19 we write out the value of the File
property.
<script runat="server" type="text/jscript" language="JScript">
Response.Write(ASPError.File);
</script>
ASP3+
ASPError.Line
The Line
property of the ASPError
object contains the line number on which the error occurred.
In Listing 9.20 we write out the value of the Line
property.
<script runat="server" type="text/jscript" language="JScript">
Response.Write(ASPError.Line);
</script>
ASP3+
ASPError.Number
The Number
property of the ASPError
object contains the standard COM error code.
In Listing 9.21 we write out the value of the Number
property.
<script runat="server" type="text/jscript" language="JScript">
Response.Write(ASPError.Number);
</script>
ASP3+
ASPError.Source
The Source
property of the ASPError
object contains the actual source code, if available, that the error occurred in.
In Listing 9.22 we write out the value of the Source
property.
<script runat="server" type="text/jscript" language="JScript">
Response.Write(ASPError.Source);
</script>
ES2+
blob(path)
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.
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.
<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>
ES2+
Core object is created with the blob.blobImage()
and blob.blobLink()
methods.
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.
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">
<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>
ES2+
cursor.column.blobImage(fileType, altText, align, width, height, border, ismap)
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.
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">
<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>
ES2+
cursor.column.blobLink(mimeType, text)
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.
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>
<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>
ES2+
callC(JSFuncName, arg1, arg2, …, argN)
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.
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.
<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>
ES2+
Core object is created with each connection of a client to your application.
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.
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.
<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>
ES2+
client.destroy()
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.
Listing 9.29 shows how to destroy the properties of your user’s client
object.
<server>
// Destroy the client properties.
client.destroy()
</server>
ES2+
client.expiration(seconds)
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.
Listing 9.30 sets the destruction of the client
object to occur after five minutes of inactivity.
<server>
// Set the expiration to 5 minutes.
client.expiration(300)
</server>
ES2+
client.
property
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.
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.
<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>
ES3+
client.unwatch(property)
The unwatch()
method of the client
object is used to turn off the watch for a particular property.
Listing 9.32 shows how the unwatch()
method is used to stop watching the user-defined property p.
<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>
ES3+
client.watch(property, function)
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.
Listing 9.33 shows how the watch()
method is used to start watching the user-defined property p.
<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>
ES3+
Core object is created when the DbPool.connection()
method is called.
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.
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.
<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>
ES3+
connection.beginTransaction()
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.
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.
<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>
ES3+
connection.commitTransaction()
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.
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.
<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>
ES3+
connection .connected()
The connected()
method of the Connection
object tells if the pool of connections to the database is still connected.
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.
<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>
ES3+
connection.cursor(
(sql)
connection.cursor(
sql, boolean)
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.
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.
<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>
ES3+
connection.execute(
statement)
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
.
Listing 9.39 deletes all rows with a UID less than the number passed to the script.
<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>
ES3+
connection .majorErrorCode()
The majorErrorMessage()
method of the Connection
object contains the ODBC or database numeric error code that is returned if an error occurs.
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.
<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>
ES3+
connection .majorErrorMessage()
The majorErrorMessage()
method of the Connection
object contains the ODBC or database string error message that is returned if an error occurs.
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.
<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>
ES3+
connection .minorErrorCode()
The minorErrorMessage()
method of the Connection
object contains the secondary ODBC or database numeric error code that is returned if an error occurs.
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.
<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>
ES3+
connection .minorErrorMessage()
The minorErrorMessage()
method of the Connection
object contains the secondary ODBC or the database string error message that is returned if an error occurs.
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.
<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);
}
ES3+
connection .prototype.
method =
name
connection .prototype.
property =
value
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.
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.
<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>
ES3+
connection .release()
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.
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.
<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>
ES3+
connection.rollbackTransaction()
The rollbackTransaction()
method of the Connection
object will undo all actions performed since the last beginTransaction()
method call.
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.
<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>
ES3+
connection.SQLTable(
(sql)
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>
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.
<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>
ES3+
connection.storedProc(
procName)
connection.storedProc(
procName,
arg1,
arg2, …,
argN)
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.
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.
<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> >
ES3+
connection.toString()
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.
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.
<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>
ES3+
connection.unwatch(
property)
The unwatch()
method of the Connection
object is used to turn off the watch for a particular property.
Listing 9.50 shows how the unwatch()
method is used to stop watching the user-defined property p.
<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>
ES3+
connection.watch(
property, function)
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.
Listing 9.51 shows how the watch()
method is used to start watching the user-defined property p.
<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>
ES2+
connection.cursor()
database.cursor()
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.
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.
<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>
ES2+
cursor.close()
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.
Listing 9.53 creates a cursor and then closes it.
<server>
// Create cursor
var currRow = myConn.cursor('SELECT areacode FROM employees WHERE uid >= '
+ client.uid);
// Close the cursor
currRow.close();
</server>
ES2+
cursor.
columnName
The columnName property of the Cursor
object is an array of objects that corresponds to the name of the columns in the cursor.
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.
<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>
ES2+
cursor.columnName(
(num)
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.
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.
<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>
ES2+
cursor.columns()
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.
Listing 9.56 shows how you can return all the column names of the columns in your cursor.
<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>
ES2+
cursor.deleteRow(
table)
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.
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.
<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>
ES2+
cursor.insertRow(
(table)
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.
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.
<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>
ES2+
cursor.next()
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
.
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.
<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>
ES2+
cursor.prototype.
method = name
cursor.prototype.
property =
value
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.
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.
<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>
ES3+
cursor.unwatch(
property)
The unwatch()
method of the Cursor
object is used to turn off the watch for a particular property.
Listing 9.61 shows how the unwatch()
method is used to stop watching the user-defined property p.
<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>
ES2+
cursor.updateRow(
(table)
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.
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.
<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>
ES3+
cursor.watch(
property, function)
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.
Listing 9.63 shows how the watch()
method is used to start watching the user-defined property p.
<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>
ES2+
Core object is created when the database.connect()
method is called.
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.
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.
<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>
ES2+
database.beginTransaction()
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.
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.
<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>
ES2+
database.commitTransaction()
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.
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.
<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>
ES2+
database.connect(
dbType,
dbInstance,
uid,
pwd,
dbName)
database.connect(
dbType,
dbInstance,
uid,
pwd,
dbName,
maxConn)
database.connect(
dbType,
dbInstance,
uid,
pwd,
dbName,
maxConn,
commitFlag)
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.
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.
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.
<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>
ES2+
database.connected()
The connected()
method of the database
object tells whether the connection to the database is still active.
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.
<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>
ES2+
database.cursor(
sql)
database.cursor(
sql,
boolean)
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.
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.
<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>
ES2+
database.disconnect()
The disconnect
method of the database
object disconnects a connection to a database.
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.
<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>
ES2+
database.execute(
statement)
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
.
Listing 9.71 deletes all rows with a UID less than the number passed to the script.
<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>
ES2+
database.majorErrorCode()
The majorErrorCode()
method of the database
object contains the ODBC or database numeric error code that is returned if an error occurs.
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.
<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>
ES2+
database.majorErrorMessage()
The majorErrorMessage()
method of the database
object contains the ODBC or database string error message that is returned if an error occurs.
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.
<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>
ES2+
database.minorErrorCode()
The minorErrorCode()
method of the database
object contains the secondary ODBC or database numeric error code that is returned if an error occurs.
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.
<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>
ES2+
database.minorErrorMessage()
The minorErrorMessage()
method of the database
object contains the secondary ODBC or database string error message that is returned if an error occurs.
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.
<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>
ES2+
database.prototype.
method =
name
database.prototype.
property =
value
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.
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.
<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>
ES2+
database.rollbackTransaction()
The rollbackTransaction()
method of the database
object will undo all actions performed since the last beginTransaction()
method call.
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.
<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>
ES2+
database.SQLTable(
sql)
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>
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.
<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>
ES3+
database.storedProc(
procName)
database.storedProc(
procName,
arg1,
arg2, …,
argN)
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.
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.
<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> >
ES3+
database.storedProcArgs(
procName)
database.storedProcArgs(
procName,
type1,
type2, …,
typeN)
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.
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.
<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>
ES2+
database.toString()
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.
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.
<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>
ES3+
database.unwatch(property)
The unwatch()
method of the database
object is used to turn off the watch for a particular property.
Listing 9.82 shows how the unwatch()
method is used to stop watching the user-defined property p.
<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>
ES3+
database.watch(property, function)
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.
Listing 9.83 shows how the watch()
method is used to start watching the user-defined property p.
<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>
ES3+
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)
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.
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.
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.
<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>
ES3+
dbpool.connect(
dbType,
dbInstance,
uid,
pwd,
dbName)
dbpool.connect(
dbType,
dbInstance,
uid,
pwd,
dbName,
maxConn)
dbpool.connect(
dbType,
dbInstance,
uid,
pwd,
dbName,
maxConn,
commitFlag)
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.
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.
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.
<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>
ES3+
dbpool.connected()
The connected()
method of the DbPool
object tells whether the pool of connections to the database is still connected.
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.
<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>
ES3+
dbpool.connection(name, seconds);
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.
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.
<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>
ES3+
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)
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.
Depending on your database, it is possible to create an instance of this object by passing a limited set of these parameters.
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.
<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>
ES3+
dbpool.disconnect()
The disconnect()
method of the DbPool
object disconnects all connections to a database within that pool.
Listing 9.89 creates a connection to an Oracle database. The next line drops the connection by 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>
ES3+
dbpool.majorErrorCode()
The majorErrorCode()
method of the DbPool
object contains the ODBC or database numeric error code that is returned if an error occurs.
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.
<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>
ES3+
dbpool.majorErrorMessage()
The majorErrorMessage()
method of the DbPool
object contains the ODBC or database string error message that is returned if an error occurs.
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.
<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>
ES3+
dbpool.minorErrorCode()
The minorErrorCode()
method of the DbPool
object contains the secondary ODBC or database numeric error code that is returned if an error occurs.
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.
<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>
ES3+
dbpool.minorErrorMessage()
The minorErrorMessage()
method of the DbPool
object contains the secondary ODBC or database string error message that is returned if an error occurs.
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.
<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>
ES3+
dbpool.prototype.
method =
name dbpool.prototype.
property =
value
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.
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.
<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>
ES3+
database.storedProcArgs(
procName)
database.storedProcArgs(
procName,
type1,
type2, …,
typeN)
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.
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.
<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>
ES3+
dbpool.toString()
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.
Listing 9.96 creates an instance of the DbPool
object. Once created, the write()
<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>
ES3+
dbpool.unwatch(
property)
The unwatch()
method of the DbPool
object is used to turn off the watch for a particular property.
Listing 9.97 shows how the unwatch()
method is used to stop watching the user-defined property p.
<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>
ES3+
dbpool.watch(property, function)
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.
Listing 9.98 shows how the watch()
method is used to start watching the user-defined property p.
<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>
ES2+
debug(expression)
debug(variable)
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.
Listing 9.99, when run in the JavaScript Application Manager’s debugger, will display the value of the request.name when encountered.
<server>
// Display the value of the name passed in the request
// to the application.
debug(request.name);
</server>
ES3+
deleteResponseHeader(key)
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.
Listing 9.100 shows how you can delete the content-type header field before it is sent back to the browser.
<server>
// Delete a field to the header.
deleteResponseHeader("content-type");
</server>
ES2+
new File(path)
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.
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.
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.
<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>
ES2+
File.byteToString(
num)
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.
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.
<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>
ES2+
Syntax
file.clearError()
The clearError()
method of the File
object clears the file error status and the value returned by the eof()
method.
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.
<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>
ES2+
file.close()
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.
Listing 9.104 shows how to open a file and then close it.
<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>
ES2+
file.constructor
The constructor
property of the File
object specifies the function that creates the object.
Listing 9.2105 shows an 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>
ES2+
file.eof()
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.
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.
<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>
ES2+
file.error()
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.
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.
<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>
ES2+
file.exists()
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.
Listing 9.108 opens a file and then checks to see whether it 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>
ES2+
file.flush()
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.
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.
<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>
ES2+
file.getLength()
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.
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.
<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>
ES2+
file.getPosition()
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.
Listing 9.111 loops through each character, printing it on a new line next to its indexed location.
<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>
ES2+
file.open(option)
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.
Listing 9.112 shows how to open a file in read
mode.
<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>
ES3+
file.prototype.method = name
file.prototype.property = value
18.117.100.89