2025-04-27 07:49:33 -04:00

474 lines
36 KiB
HTML

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html dir=ltr><head><title>Accessing a Data Source</title>
<SCRIPT LANGUAGE="JavaScript">
<!--
TempString = navigator.appVersion
if (navigator.appName == "Microsoft Internet Explorer"){
// Check to see if browser is Microsoft
if (TempString.indexOf ("4.") >= 0){
// Check to see if it is IE 4
document.writeln('<link rel="stylesheet" type="text/css" href="/iishelp/common/coua.css">');
}
else {
document.writeln('<link rel="stylesheet" type="text/css" href="/iishelp/common/cocss.css">');
}
}
else if (navigator.appName == "Netscape") {
// Check to see if browser is Netscape
document.writeln('<link rel="stylesheet" type="text/css" href="/iishelp/common/coua.css">');
}
else
document.writeln('<link rel="stylesheet" type="text/css" href="/iishelp/common/cocss.css">');
//-->
</script>
<META NAME="DESCRIPTION" CONTENT="This topic describes how to use ASP and ActiveX Data Objects (ADO) to add database access to your Web pages."><META HTTP-EQUIV="Content-Type" content="text/html; charset=Windows-1252">
<META HTTP-EQUIV="PICS-Label" CONTENT='(PICS-1.1 "<http://www.rsac.org/ratingsv01.html>" l comment "RSACi North America Server" by "inet@microsoft.com <mailto:inet@microsoft.com>" r (n 0 s 0 v 0 l 0))'>
<META NAME="MS.LOCALE" CONTENT="EN-US">
<META NAME="MS-IT-LOC" Content="Internet Information Services">
</head>
<body bgcolor="#FFFFFF" text="#000000">
<font face="Verdana,Arial,Helvetica">
<h1><a name="H1_37770897">Accessing a Data Source</a></h1>
<p>ActiveX Data Objects (ADO) are an easy-to-use yet extensible technology for adding database access to your Web pages. You can use ADO to write compact and scalable scripts for connecting to OLE DB compliant data sources, such as databases, spreadsheets, sequential data files, or e-mail directories. OLE DB is a system-level programming interface that provides standard set of COM interfaces for exposing database management system functionality. With ADO's object model you can easily access these interfaces (using scripting languages, such as VBScript or JScript) to add database functionality to your Web applications. In addition, you can also use ADO to access Open Database Connectivity (ODBC) compliant databases.</p>
<p>If you are a scripter with a modest understanding of database connectivity, you will find ADO's command syntax uncomplicated and easy-to-use. If you are an experienced developer you will appreciate the scalable, high-performance access ADO provides to a variety of data sources.</p>
<P>For more information about ADO, visit the <A HREF="http://www.microsoft.com/isapi/redir.dll?prd=mdac" TARGET="_blank">Microsoft Universal Data Access (UDA) Web site</A>.</P>
<h2><a name="H2_37771874">Creating a Connection String</a></h2>
<p>The first step in creating a Web data application is to provide a way for ADO to locate and identify your data source. This is accomplished by means of a <EM>connection string</EM>, a series of semicolon delimited arguments that define parameters such as the data source provider and the location of the data source. ADO uses the connection string to identify the OLE DB <EM>provider</EM> and to direct the provider to the data source. The provider is a component that represents the data source and exposes information to your application in the form of rowsets.</P>
<P>The following table lists OLE DB connection strings for several common data sources:</P>
<TABLE border="1" cellpadding="4" cellspacing="1" width="60%">
<TR>
<TD bgcolor="#C0C0C0" align="Left" valign="top"><STRONG>Data Source</STRONG></TD>
<TD bgcolor="#C0C0C0" align="Left" valign="top"><STRONG>OLE DB Connection String</STRONG></TD>
</TR>
<TR>
<TD>Microsoft&#174; Access</TD>
<TD>Provider=Microsoft.Jet.OLEDB.4.0;Data Source=<EM>physical path to .mdb file</EM></TD>
</TR>
<TR>
<TD>Microsoft SQL Server</TD>
<TD>Provider=SQLOLEDB.1;Data Source=<EM>path to database on server</EM></TD>
</TR>
<TR>
<TD>Oracle</TD>
<TD>Provider=MSDAORA.1;Data Source=<EM>path to database on server</EM></TD>
</TR>
<TR>
<TD>Microsoft Indexing Service</TD>
<TD>Provider=MSIDXS.1;Data Source=<EM>path to file</EM></TD>
</TR>
</TABLE>
<P>To provide for backward compatibility, the OLE DB Provider for ODBC supports ODBC connection string syntax. The following table lists commonly used ODBC connection strings: </P>
<TABLE border="1" cellpadding="4" cellspacing="1" width="60%">
<TR>
<TD bgcolor="#C0C0C0" align="Left" valign="top"><STRONG>Data Source Driver</STRONG></TD>
<TD bgcolor="#C0C0C0" align="Left" valign="top"><STRONG>ODBC Connection String</STRONG></TD>
</TR>
<TR>
<TD>Microsoft Access</TD>
<TD>Driver={Microsoft Access Driver (*.mdb)};DBQ=<EM>physical path to .mdb file</EM></TD>
</TR>
<TR>
<TD>SQL Server</TD>
<TD>DRIVER={SQL Server};SERVER=<EM>path to server</EM></TD>
</TR>
<TR>
<TD>Oracle</TD>
<TD>DRIVER={Microsoft ODBC for Oracle};SERVER=<EM>path to server</EM></TD>
</TR>
<TR>
<TD>Microsoft Excel</TD>
<TD>Driver={Microsoft Excel Driver (*.xls)};DBQ=<EM>physical path to .xls file</EM>; DriverID=278</TD>
</TR>
<TR>
<TD>Microsoft Excel 97</TD>
<TD>Driver={Microsoft Excel Driver (*.xls)};DBQ=<EM>physical path to .xls file</EM>;DriverID=790</TD>
</TR>
<TR>
<TD>Paradox</TD>
<TD>Driver={Microsoft Paradox Driver (*.db)};DBQ=<EM>physical path to .db file</EM>;DriverID=26</TD>
</TR>
<TR>
<TD>Text</TD>
<TD>Driver={Microsoft Text Driver (*.txt;*.csv)};DefaultDir=<EM>physical path to .txt file</EM></TD>
</TR>
<TR>
<TD>Microsoft Visual FoxPro&#174; (with a database container) </TD>
<TD>Driver={Microsoft Visual FoxPro Driver};SourceType=DBC;SourceDb=<EM>physical path to .dbc file</EM></TD>
</TR>
<TR>
<TD>Microsoft Visual FoxPro (without a database container) </TD>
<TD>Driver={Microsoft Visual FoxPro Driver};SourceType=DBF;SourceDb=<EM>physical path to .dbf file</EM></TD>
</TR>
</TABLE>
<BR>
<p><strong>Note</strong>&nbsp;&nbsp;&nbsp;Connection strings that use a UNC path to refer to a data source located on a remote computer can pose a potential security issue. To prevent unauthorized access of your data source, create a Windows account for computers requiring access to the data and then apply appropriate NTFS permissions to the data source. For more information, see <A HREF="../core/iintfsc.htm">Securing Your Files with NTFS</A>.</p>
<H2>Advanced Issues to Consider When Designing Web Data Applications</H2>
<p>For performance and reliability reasons, it is strongly recommended that you use a client-server database engine for the deployment of data driven Web applications that require high-demand access from more than approximately 10 concurrent users. Although ADO works with any OLE DB compliant data source, it has been extensively tested and is designed to work with client server databases such as Microsoft SQL Server or Oracle.</p>
<p>ASP supports shared file databases (Microsoft Access or Microsoft FoxPro) as valid data sources. Although some examples in the ASP documentation use a <em>shared file</em> database, it is recommended that these types of database engines be used only for development purposes or limited deployment scenarios. Shared file databases may not be as well suited as client-server databases for very high-demand, production-quality Web applications.</p>
<p>If you are developing an ASP database application intended to connect to a remote SQL Server database you should also be aware of the following issues:</p>
<ul>
<li><strong>Choosing Connection Scheme for SQL Server</strong>&nbsp;You can choose between the TCP/IP Sockets and Named Pipes methods for accessing a remote SQL Server database. With Named Pipes, database clients must be authenticated by Windows before establishing a connection, raising the possibility that a remote computer running named pipes might deny access to a user who has the appropriate SQL Server access credentials, but does not have a Windows user account on that computer. Alternatively, connections using TCP/IP Sockets connect directly to the database server, without connecting through an intermediary computer&#151;as is the case with Named Pipes. And because connections made with TCP/IP Sockets connect directly to the database server, users can gain access through SQL Server authentication, rather than Windows authentication.</li>
<li><STRONG>ODBC 80004005 Error</STRONG>&nbsp;If the connection scheme for accessing SQL Server is not set correctly, users viewing your database application may receive an ODBC 80004005 error message. To correct this situation, try using a local named pipe connection instead of a network named pipe connection if SQL Server is running on the same computer as IIS. Windows
XP security rules will not be enforced because the pipe is a local connection rather than a network connection, which can be impersonated by the anonymous user account. Also, in the SQL Server connection string (either in the Global.asa file or in a page-level script), change the parameter <STRONG>SERVER=<EM>server name</EM></STRONG> to <STRONG>SERVER=(local)</STRONG>. The keyword (local) is a special parameter recognized by the SQL Server ODBC driver. If this solution does not work, then try to use a non-authenticated protocol between IIS and SQL Server, such as TCP/IP sockets. This protocol will work when SQL Server is running locally or on remote computer.</li>
<p><strong>Note</strong>&nbsp;&nbsp;&nbsp;To improve performance when connecting to a remote databases, use TCP/IP Sockets.</p>
<li><strong>SQL Server Security</strong>&nbsp;If you use SQL Server's <em>Integrated</em> or <em>Mixed</em> security features, and the SQL Server database resides on a remote server, you will not be able to use integrated Windows authentication. Specifically, you cannot forward integrated Windows authentication credentials to the remote computer. This means that you may have to use Basic authentication, which relies on the user to provide user name and password information.</li>
</ul>
<p>For more information about these issues, visit the <a href="http://www.microsoft.com/isapi/redir.dll?prd=support&sbp=portal" target="_blank">Microsoft Product Support Services Web site</a>.</p>
<h2><a name="H2_37777925">Connecting to a Data Source</a></h2>
<p>ADO provides the <strong>Connection</strong> object for establishing and managing connections between your applications and OLE DB compliant data sources or ODBC compliant databases. The <strong>Connection</strong> object features properties and methods you can use to open and close database connections, and to issue queries for updating information.</p>
<p>To establish a database connection, you first create an instance of the <strong>Connection</strong> object. For example, the following script instantiates the <strong>Connection</strong> object and proceeds to open a connection:</p>
<pre>&lt;%
'Create a connection object.
Set cnn = Server.CreateObject(&quot;ADODB.Connection&quot;)
'Open a connection using the OLE DB connection string.
cnn.Open &quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MarketData\ProjectedSales.mdb&quot;
%&gt;</pre>
<p><strong>Note</strong>&nbsp;&nbsp;&nbsp;The connection string does not contain spaces before or after the equal sign (=).</p>
<p>In this case, the <strong>Connection </strong>object's <strong>Open</strong> method refers to the connection string.</p>
<h2><a name="H2_37779470">Executing SQL Queries with the Connection Object</a></h2>
<p>With the <strong>Execute</strong> method of the <strong>Connection</strong> object you can issue commands to the data sources, such as Structured Query Language (SQL) queries. (SQL, an industry standard language for communicating with databases, defines commands for retrieving and updating information.) The <STRONG>Execute</STRONG> method can accept parameters that specify the command (or query), the number of data records affected, and the type of command being used. </p>
<p>The following script uses the <strong>Execute</strong> method to issue a query in the form of a SQL <strong>INSERT</strong> command, which inserts data into a specific database table. In this case, the script block inserts the name <EM>Jose Lugo</EM> into a database table named <EM>Customers</EM>.</p>
<pre>&lt;%
'Define the OLE DB connection string.
strConnectionString = &quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Employees.mdb&quot;
'Instantiate the Connection object and open a database connection.
Set cnn = Server.CreateObject(&quot;ADODB.Connection&quot;)
cnn.Open strConnectionString
'Define SQL SELECT statement.
strSQL = &quot;INSERT INTO Customers (FirstName, LastName) VALUES ('Jose','Lugo')&quot;
'Use the Execute method to issue a SQL query to database.
cnn.Execute strSQL,,adCmdText + adExecuteNoRecords
%&gt;</pre>
<P>Note that two parameters are specified in the statement used to execute the query: <STRONG>adCmdText</STRONG> and <STRONG>adExecuteNoRecords</STRONG>. The optional <STRONG>adCmdText</STRONG> parameter specifies the type of command, indicating that the provider should evaluate the query statement (in this case, a SQL query) as a textual definition of a command. The <STRONG>adExecuteNoRecords</STRONG> parameter instructs ADO to not create a set of data records if there are no results returned to the application. This parameter works only with command types defined as a text definition, such as SQL queries, or stored database procedures. Although the <STRONG>adCmdText</STRONG> and <STRONG>adExecuteNoRecords</STRONG> parameters are optional, you should specify theses parameters when using the <STRONG>Execute</STRONG> method to improve the performance of your data application.</P>
<p><strong><FONT COLOR="#0000FF">Important</FONT></strong>&nbsp;&nbsp;&nbsp;ADO parameters, such as <STRONG>adCmdText</STRONG>, need to be defined before you can use them in a script. A convenient way to define parameters is to use a <EM>component type library</EM>, which is a file containing definitions for all ADO parameters. To implement a component type library, it must first be declared. Add the following the &lt;METADATA&gt; tag to your .asp file or Global.asa file to declare the ADO type library:
<PRE>&lt;!--METADATA NAME=&quot;Microsoft ActiveX Data Objects 2.5 Library&quot; TYPE=&quot;TypeLib&quot; UUID=&quot;{00000205-0000-0010-8000-00AA006D2EA4}&quot;--&gt;</PRE>
<p>For details about implementing component type libraries, see the <A HREF="iiwavar.htm#usingconstants">Using Constants</A> section of the <A HREF="iiwavar.htm">Using Variables and Constants</A> topic.</p>
<p>In addition to the SQL <strong>INSERT</strong> command, you can use the SQL <strong>UPDATE</strong> and <strong>DELETE</strong> commands to change and remove database information.</p>
<p>With the SQL <strong>UPDATE</strong> command you can change the values of items in a database table. The following script uses the <strong>UPDATE</strong> command to change the <code>Customers</code> table's <code>FirstName</code> fields to <code>Jeff</code> for every <code>LastName </code>field containing the last name <code>Smith</code>.</p>
<pre>&lt;%
Set cnn = Server.CreateObject(&quot;ADODB.Connection&quot;)
cnn.Open &quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Employees.mdb&quot;
cnn.Execute &quot;UPDATE Customers SET FirstName = 'Jeff' WHERE LastName = 'Smith' &quot;,,adCmdText + adExecuteNoRecords
%&gt;</pre>
<p>To remove specific records from a database table, use the SQL <strong>DELETE</strong> command. The following script removes all rows from the Customers table where the last name is <code>Smith</code>:</p>
<pre>&lt;%
Set cnn = Server.CreateObject(&quot;ADODB.Connection&quot;)
cnn.Open &quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Employees.mdb&quot;
cnn.Execute &quot;DELETE FROM Customers WHERE LastName = 'Smith'&quot;,,adCmdText + adExecuteNoRecords
%&gt;</pre>
<p><strong>Note</strong>&nbsp;&nbsp;&nbsp;You must be careful when using the SQL <strong>DELETE</strong> command. A <strong>DELETE </strong>command without an accompanying <strong>WHERE</strong> clause will delete all rows from a table. Be sure to include a SQL <strong>WHERE</strong> clause, which specifies the exact rows to be deleted.</p>
<h2><a name="H2_37782547">Using the Recordset Object for Manipulating Results</a></h2>
<p>For retrieving data, examining results, and making changes to your database, ADO provides the <strong>Recordset</strong> object. As its name implies, the <strong>Recordset</strong> object has features that you can use, depending on your query constraints, for retrieving and displaying a set of database rows, or <em>records</em>. The <strong>Recordset</strong> object maintains the position of each record returned by a query, thus enabling you to step through results one item at a time.</p>
<h3><a name="H3_37784801">Retrieving a Record Set</a></h3>
<p>Successful Web data applications employ both the <strong>Connection</strong> object, to establish a link, and the <strong>Recordset</strong> object, to manipulate returned data. By combining the specialized functions of both objects you can develop database applications to carry out almost any data handling task. For example, the following server-side script uses the <strong>Recordset</strong> object to execute a SQL <strong>SELECT</strong> command. The <strong>SELECT</strong> command retrieves a specific set of information based on query constraints. The query also contains a SQL <strong>WHERE</strong> clause, used to narrow down a query to a specific criterion. In this example, the <strong>WHERE</strong> clause limits the query to all records containing the last name <em>Smith</em> from the <em>Customers</em> database table.</p>
<pre>&lt;%
'Establish a connection with data source.
strConnectionString = &quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Employees.mdb&quot;
Set cnn = Server.CreateObject(&quot;ADODB.Connection&quot;)
cnn.Open strConnectionString
'Instantiate a Recordset object.
Set rstCustomers = Server.CreateObject(&quot;ADODB.Recordset&quot;)
'Open a recordset using the Open method
'and use the connection established by the Connection object.
strSQL = &quot;SELECT FirstName, LastName FROM Customers WHERE LastName = 'Smith' &quot;
rstCustomers.Open strSQL, cnn
'Cycle through record set and display the results
'and increment record position with MoveNext method.
Set objFirstName = rstCustomers(&quot;FirstName&quot;)
Set objLastName = rstCustomers(&quot;LastName&quot;)
Do Until rstCustomers.EOF
Response.Write objFirstName &amp; &quot; &quot; &amp; objLastName &amp; &quot;&lt;BR&gt;&quot;
rstCustomers.MoveNext
Loop
%&gt;</pre>
<p>Note that in the previous example, the <strong>Connection</strong> object established the database connection, and the <strong>Recordset</strong> object used the same connection to retrieve results from the database. This method is advantageous when you need to precisely configure the way in which the link with the database is established. For example, if you needed to specify the time delay before a connection attempt aborts, you would need to use the <strong>Connection</strong> object to set this property. However, if you just wanted to establish a connection using ADO's default connection properties, you could use <strong>Recordset</strong> object's <strong>Open</strong> method to establish a link:</p>
<pre>&lt;%
strConnectionString = &quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Employees.mdb&quot;
strSQL = &quot;SELECT FirstName, LastName FROM Customers WHERE LastName = 'Smith' &quot;
Set rstCustomers = Server.CreateObject(&quot;ADODB.Recordset&quot;)
'Open a connection using the Open method
'and use the connection established by the Connection object.
rstCustomers.Open strSQL, strConnectionString
'Cycle through the record set, display the results,
'and increment record position with MoveNext method.
Set objFirstName = rstCustomers(&quot;FirstName&quot;)
Set objLastName = rstCustomers(&quot;LastName&quot;)
Do Until rstCustomers.EOF
Response.Write objFirstName &amp; &quot; &quot; &amp; objLastName &amp; &quot;&lt;BR&gt;&quot;
rstCustomers.MoveNext
Loop
%&gt;</pre>
<p>When you establish a connection using the <strong>Recordset</strong> object's <strong>Open</strong> method to establish a connection, you are implicitly using the <strong>Connection</strong> object to secure the link. For more information, see Microsoft ActiveX Data Objects (ADO) documentation available from the <A HREF="http://www.microsoft.com/isapi/redir.dll?prd=mdac" TARGET="_blank">Microsoft Universal Data Access Web site</A>.</p>
<p><strong>Note</strong>&nbsp;&nbsp;&nbsp;To significantly improve the performance of your ASP database applications, consider caching the recordset in <strong>Application</strong> state. For more information, see <a href="eadg6cbl.htm">Caching Data</a>.
</p>
<P>It is often useful to count the number of records returned in a recordset. The <STRONG>Open</STRONG> method of the <STRONG>Recordset</STRONG> object enables you to specify an optional <EM>cursor</EM> parameter that determines how the underlying provider retrieves and navigates the recordset. By adding the <STRONG>adOpenKeyset</STRONG> cursor parameter to the statement used to execute the query, you enable the client application to fully navigate the recordset. As a result, the application can use the <STRONG>RecordCount</STRONG> property to accurately count the number of records in the recordset. See the following example:</P>
<pre>&lt;%
Set rs = Server.CreateObject(&quot;ADODB.Recordset&quot;)
rs.Open &quot;SELECT * FROM NewOrders&quot;, &quot;Provider=Microsoft.Jet.OLEDB.3.51;Data Source='C:\CustomerOrders\Orders.mdb'&quot;, adOpenKeyset, adLockOptimistic, adCmdText
'Use the RecordCount property of the Recordset object to get count.
If rs.RecordCount &gt;= 5 then
Response.Write &quot;We've received the following &quot; &amp; rs.RecordCount &amp; &quot; new orders&lt;BR&gt;&quot;
Do Until rs.EOF
Response.Write rs(&quot;CustomerFirstName&quot;) &amp; &quot; &quot; &amp; rs(&quot;CustomerLastName&quot;) &amp; &quot;&lt;BR&gt;&quot;
Response.Write rs(&quot;AccountNumber&quot;) &amp; &quot;&lt;BR&gt;&quot;
Response.Write rs(&quot;Quantity&quot;) &amp; &quot;&lt;BR&gt;&quot;
Response.Write rs(&quot;DeliveryDate&quot;) &amp; &quot;&lt;BR&gt;&lt;BR&gt;&quot;
rs.MoveNext
Loop
Else
Response.Write &quot;There are less than &quot; &amp; rs.RecordCount &amp; &quot; new orders.&quot;
End If
rs.Close
%&gt;</pre>
<h2><a name="H2_37787604">Improving Queries with the Command Object</a></h2>
<p>With the ADO <strong>Command</strong> object you can execute queries in the same way as queries executed with the <strong>Connection</strong> and <strong>Recordset</strong> object, except that with the <strong>Command</strong> object you can prepare, or compile, your query on the database source and then repeatedly reissue the query with a different set of values. The benefit of compiling queries in this manner is that you can vastly reduce the time required to reissue modifications to an existing query. In addition, you can leave your SQL queries partially undefined, with the option of altering portions of your queries just prior to execution.</p>
<p>The <strong>Command</strong> object's <strong>Parameters</strong> collection saves you the trouble of reconstructing your query each time you want to reissue your query. For example, if you need to regularly update supply and cost information in your Web-based inventory system, you can predefine your query in the following way:</p>
<pre>&lt;%
'Open a connection using Connection object. Notice that the Command object
'does not have an Open method for establishing a connection.
strConnectionString = &quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Inventory.mdb&quot;
Set cnn = Server.CreateObject(&quot;ADODB.Connection&quot;)
cnn.Open strConnectionString
'Instantiate Command object; use ActiveConnection property to attach
'connection to Command object.
Set cmn= Server.CreateObject(&quot;ADODB.Command&quot;)
Set cmn.ActiveConnection = cnn
'Define SQL query.
cmn.CommandText = &quot;INSERT INTO Inventory (Material, Quantity) VALUES (?, ?)&quot;
'Save a prepared (or pre-compiled) version of the query specified in CommandText
'property before a Command object's first execution.
cmn.Prepared = True
'Define query parameter configuration information.
cmn.Parameters.Append cmn.CreateParameter(&quot;material_type&quot;,adVarChar, ,255 )
cmn.Parameters.Append cmn.CreateParameter(&quot;quantity&quot;,adVarChar, ,255 )
'Define and execute first insert.
cmn(&quot;material_type&quot;) = &quot;light bulbs&quot;
cmn(&quot;quantity&quot;) = &quot;40&quot;
cmn.Execute ,,adCmdText + adExecuteNoRecords
'Define and execute second insert.
cmn(&quot;material_type&quot;) = &quot;fuses&quot;
cmn(&quot;quantity&quot;) = &quot;600&quot;
cmn.Execute ,,adCmdText + adExecuteNoRecords
.
.
.
%&gt;</pre>
<p><strong><FONT COLOR="#0000FF">Important</FONT></strong>&nbsp;&nbsp;&nbsp;ADO parameters, such as <STRONG>adCmdText</STRONG>, are simply variables, this means that before using an ADO parameter in a data access script you need to define its value. Since ADO uses a large number of parameters, it is easier to define parameters by means of a <EM>component type library</EM>, a file containing definitions for every ADO parameter and constant. For details about implementing ADO's type library, see the <A HREF="iiwavar.htm#usingconstants">Using Constants</A> section of the <A HREF="iiwavar.htm">Using Variables and Constants</A> topic.</p>
<p>In the previous example, you will note that the script repeatedly constructs and reissues a SQL query with different values, without having to redefine and resend the query to the database source. Compiling your queries with the <strong>Command</strong> object also offers you the advantage of avoiding problems that can arise from concatenating strings and variables to form SQL queries. In particular, by using the <strong>Command</strong> object's <strong>Parameter</strong> collection, you can avoid problems related to defining certain types of string, date, and time variables. For example, SQL query values containing apostrophes (') can cause a query to fail:</p>
<pre> strSQL = &quot;INSERT INTO Customers (FirstName, LastName) VALUES ('Robert','O'Hara')&quot; </pre>
<p>Note that the last name <strong>O'Hara</strong> contains an apostrophe, which conflicts with the apostrophes used to denote data in the SQL <strong>VALUES</strong> keyword. By binding the query value as a <strong>Command</strong> object parameter, you avoid this type of problem.</p>
<h2><a name="H2_37790742">Combining HTML Forms and Database Access</a></h2>
<p>Web pages containing HTML forms can enable users to remotely query a database and retrieve specific information. With ADO you can create surprisingly simple scripts that collect user form information, create a custom database query, and return information to the user. Using the ASP <strong>Request</strong> object, you can retrieve information entered into an HTML form and incorporate this information into your SQL statements. For example, the following script block inserts information supplied by an HTML form into a table. The script collects the user information with the <strong>Request</strong> object 's <strong>Form </strong>collection.</p>
<pre>&lt;%
'Open a connection using Connection object. The Command object
'does not have an Open method for establishing a connection.
strConnectionString = &quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\CompanyCatalog\Seeds.mdb&quot;
Set cnn = Server.CreateObject(&quot;ADODB.Connection&quot;)
cnn.Open strConnectionString
'Instantiate Command object
'and use ActiveConnection property to attach
'connection to Command object.
Set cmn= Server.CreateObject(&quot;ADODB.Command&quot;)
Set cmn.ActiveConnection = cnn
'Define SQL query.
cmn.CommandText = &quot;INSERT INTO MySeedsTable (Type) VALUES (?)&quot;
'Define query parameter configuration information.
cmn.Parameters.Append cmn.CreateParameter(&quot;type&quot;,adVarChar, ,255)
'Assign input value and execute update.
cmn(&quot;type&quot;) = Request.Form(&quot;SeedType&quot;)
cmn.Execute ,,adCmdText + adExecuteNoRecords
%&gt;</pre>
<p>For more information about forms and using the ASP <strong>Request </strong>object, see <a href="iiwaform.htm">Processing User Input</a>.</p>
<h2><a name="H2_37792280">Managing Database Connections</a></h2>
<p>One of the main challenges of designing a sophisticated Web database application, such as an online order entry application that services thousands of customers, is properly managing database connections. Opening and maintaining database connections, even when no information is being transmitted, can severely strain a database server's resources and result in connectivity problems. Well designed Web database applications recycle database connections and compensate for delays due to network traffic.</p>
<h3><a name="H3_37793252">Timing Out a Connection</a></h3>
<p>A database server experiencing a sudden increase in activity can become backlogged, greatly increasing the time required to establish a database connection. As a result, excessive connection delays can reduce the performance of your database application.</p>
<p>With the <strong>Connection</strong> object's <strong>ConnectionTimeout</strong> you can limit the amount of time that your application waits before abandoning a connection attempt and issuing an error message. For example, the following script sets the <strong>ConnectionTimeout</strong> property to wait twenty seconds before cancelling the connection attempt:</p>
<pre>Set cnn = Server.CreateObject(&quot;ADODB.Connection&quot;)
cnn.ConnectionTimeout = 20
cnn.Open &quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Inventory.mdb&quot;
</pre>
<p>The default for the <strong>ConnectionTimeout</strong> property is 30 seconds.</p>
<p><strong>Note</strong>&nbsp;&nbsp;&nbsp;Before incorporating the <strong>ConnectionTimeout</strong> property into your database applications, make sure that your connection provider and data source support this property.</p>
<h3><a name="H3_37794400">Pooling Connections</a></h3>
<p>Connection pooling enables your Web application to use a connection from a <EM>pool</EM>, or reservoir of free connections that do not need to be reestablished. After a connection has been created and placed in a pool, your application reuses that connection without having to perform the connection process. This can result in significant performance gains, especially if your application connects over a network or repeatedly connects and disconnects. In addition, a pooled connection can be used repeatedly by multiple applications.</P>
<H4>OLE DB Session Pooling</H4>
<P>OLE DB has a pooling feature, called <EM>session pooling</EM>, optimized for improving connectivity performance in large Web database applications. Session pooling preserves connection security and other properties. A pooled connection is only reused if matching requests are made from both sides of the connection. By default, the OLE DB providers for Microsoft SQL server and Oracle support session pooling. This means that you do not have to configure your application, server, or database to use session pooling. However, if your provider does not support session pooling by default, you need to create a registry setting to enable session pooling. For more information about session pooling, see the OLE DB 2.0 Software Development Kit (SDK) documentation.</P>
<H4>ODBC Connection Pooling</H4>
<p>If you want your ODBC driver to participate in connection pooling you must configure your specific database driver and then set the driver's <strong><strong>CPTimeout</strong> </strong>property in the Windows registry. The <strong>CPTimeout</strong> property determines the length of time that a connection remains in the connection pool. If the connection remains in the pool longer than the duration set by <strong>CPTimeout</strong>, the connection is closed and removed from the pool. The default value for <strong>CPTimeout</strong> is 60 seconds.</p>
<p>You can selectively set the <strong>CPTimeout</strong> property to enable connection pooling for a specific ODBC database driver by creating a registry key with the following settings:</p>
<pre>
\HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\driver-name\CPTimeout = timeout
(REG_SZ, units are in seconds)
</pre>
<p>For example, the following key sets the connection pool timeout to 180 seconds (3 minutes) for the SQL Server driver.</p>
<pre>\HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\SQL Server\CPTimeout = 180</pre>
<p class="note"><strong>Note</strong>&nbsp;&nbsp;&nbsp;By default, your Web server activates connection pooling for SQL Server by setting <strong>CPTimeout</strong> to 60 seconds.</p>
<h3><a name="H3_37796346">Using Connections Across Multiple Pages</a></h3>
<p>Although you can reuse a connection across multiple pages by storing the connection in ASP's <strong>Application</strong> object, doing so may unnecessarily keep open a connection open, defeating the advantages of using connection pooling. If you have many users that need to connect to the same ASP database application, a better approach is to reuse a database connection string across several Web pages by placing the string in ASP's <strong>Application</strong> object. For example, you can specify a connection string in the Global.asa file's Application_OnStart event procedure, as in the following script:</p>
<pre>
Application(&quot;ConnectionString&quot;) = &quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Inventory.mdb&quot;
</pre>
<p>Then in each ASP file that accesses the database, you can write</p>
<pre>&lt;OBJECT RUNAT=SERVER ID=cnn PROGID=&quot;ADODB.Connection&quot;&gt;&lt;/OBJECT&gt;</pre>
<p>to create an instance of the connection object for the page, and use the script</p>
<pre>cnn.Open Application(&quot;ConnectionString&quot;)</pre>
<p>to open the connection. At the end of the page, you close the connection with</p>
<pre>cnn.Close</pre>
<p>In the case of an individual user who needs to reuse a connection across multiple Web pages, you may find it more advantageous to use the <strong>Session</strong> object rather than the <strong>Application </strong>object for storing the connection string.</p>
<h3><a name="H3_37797541">Closing Connections</a></h3>
<p>To make the best use of connection pooling, explicitly close database connections as soon as possible. By default, a connection terminates after your script finishes execution. However, by explicitly closing a connection in your script after it is no longer needed, you reduce demand on the database server and make the connection available to other users.</p>
<p>You can use <strong>Connection</strong> object's <strong>Close</strong> method to explicitly terminate a connection between the <strong>Connection </strong>object and the database. The following script opens and closes a connection:</p>
<pre>&lt;%
strConnectionString = &quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Inventory.mdb&quot;
Set cnn = Server.CreateObject(&quot;ADODB.Connection&quot;)
cnn.Open strConnectionString
cnn.Close
%&gt;
</pre>
<hr class="iis" size="1">
<p align="center"><em><a href="/iishelp/common/colegal.htm">&copy; 1997-2001 Microsoft Corporation. All rights reserved.</a></em></p>
</font>
</font>
</body>
</html>