Home > Articles > Programming > Visual Basic

  • Print
  • + Share This
This chapter is from the book

Database Access with Active Server Pages

Suppose that you want to publish the contents of a database on the Web. With ASP, you can use ADO objects in your VBScript code to access databases. As discussed in Chapter 28, "Using ActiveX Data Objects (ADO)," to access a database, you first need to identify a data source. The actual database can be located on the Web server itself or on another machine, as long as you can connect to it via a data source.

When setting up data sources for use with ASP, you generally should use a System Data Source Name (DSN) rather than a User DSN. The System DSN allows the data source to be available to the Web server at all times, not just when a certain user is logged in.

    See "Setting Up a Data Source," p. 613.


You can also use a DSN-less connection that does not require you to set up a data source. This is also discussed in Chapter 28.

In this section, the examples assume that the BIBLIO data source has been set up, as described in Chapter 26, "Using Data Access Objects (DAO)."

    See "Setting Up a DAO Project," p. 567.


If you have problems connecting to a Microsoft SQL Server data source using standard security on a different machine from the Web server, you might receive an error such as Connection Open error in the function CreateFile(). This means that the NT account making the connection (usually the I_USR account) does not have sufficient authority on the NT SQL server.

Querying a Database

With what you have read up to this point, you have all of the knowledge necessary to run an ADO database query and display the results in a Web page. However, even a small database such as BIBLIO.MDB has many records. Therefore, you need to provide some way to query the database for just the records that the user wants to see, which of course means you need to accept user input.

Setting Up a Sample Query Page

The <FORM> tag, built in to the HTML language, allows user input to be sent to the Web server. Let's set up an HTML form, DBQUERY.HTM, that allows the user to enter an author's name to search for. Simply enter the HTML code in Listing 31.3 and save it on the Web server.

Listing 31.3  DBQUERY.HTM is a Standard HTML Form

<H1>Biblio Database Search</H1><HR>


Enter Author to search for:



An HTML form consists of different types of <INPUT> tags, which appear in the user's browser as data entry fields. The contents of these fields are sent to the Web server when the user "submits" a form.

Note that the code in Listing 31.3 is not an ASP page. It contains no VBScript statements and has the standard .HTM extension. It simply submits an HTML form to an ASP page called DBSEARCH.ASP. The purpose of DBSEARCH.ASP, shown in Listing 31.4, is to perform the actual search.

Writing DBSEARCH.ASP is fairly easy, as well. You basically have three things to do:

  1. Retrieve the value the user wants to search for from the form field txtSearch, and use it to build a query.

  2. Execute the query using ADO to obtain a recordset.

  1. Send the contents of the recordset back to the user's browser.

The code for DBSEARCH.ASP, shown in Listing 31.4, uses the Like statement in the SQL query.

Listing 31.4  DBSEARCH.ASP Performs the Database Search

   Dim cn
   Dim rs
   Dim sSQL
   Dim sSearchString

   sSearchString = Request.Form("txtSearch")

   If sSearchString = "" Then
      Response.Write ("No search string entered!")
   End If

   Set cn = Server.CreateObject("ADODB.Connection")
        cn.Open "DSN=BIBLIO"

   sSQL = sSQL & "'" & sSearchString & "%' ORDER BY AUTHOR"

   Set rs = cn.Execute(sSQL)

<TR>Author's Name</TR>

   While Not rs.EOF
      Response.Write ("<TR><TD>")
      Response.Write rs.Fields("Author")
      Response.Write ("<TD></TR>")

   Set rs = Nothing
   Set cn = Nothing

After you have created DBQUERY.HTM and DBSEARCH.ASP, you should be able to open the URL for DBQUERY.HTM, enter a few letters of the alphabet, and have the matching records displayed in the browser (see Figures 31.4 and 31.5).

Figure 31.4.

This page contains a standard HTML form that allows the user to enter a value and post it to an ASP page for processing.

Figure 31.5

VBScript code on the server returns the contents of a recordset in the form of an HTML table.


In your database search example, you used separate ASP and HTM files. You could have just as easily combined the two files into a single ASP file. The only change you would need to make would be to have the form action refer to the same page. You might also want to use an if statement to check for the form value to see if you need to display the results:

<% If Request.Form("txtSearch") <> "" Then DisplayResults %>

The preceding line of code assumes that you have written a custom function, DisplayResults, to execute the query.

Displaying Data with Drill-Down Links

The code in Listings 31.3 and 31.4 uses an HTML form field to retrieve the search criteria from the user. The user must first type a value into a text box and press a button. However, many times it is more convenient to use hyperlinks to perform database navigation. For example, suppose that you want to allow the user to click an author's name in the list of authors to display the books by that author. You can do this very easily by generating hyperlinks for each author. To generate these hyperlinks, modify the While loop code from Listing 31.4 as follows:

   While Not rs.EOF
      Response.Write ("<TR><TD><A HREF=author.asp?id=")
      Response.Write rs.fields("AU_ID") & ">"
      Response.Write rs.Fields("Author")
      Response.Write ("</A><TD></TR>")

Run a search, and each author's name in the resulting list should appear as a hyperlink to a new ASP file, AUTHOR.ASP. If you choose View Source in your browser, you will see that each hyperlink is unique:

<A HREF=author.asp?id=16061>Jackson, Bruce</A>

The preceding line of HTML passes a parameter id to the ASP page AUTHOR.ASP. If you click the hyperlink, the browser will ask the server for this URL:


Note that the URL includes the id parameter, which is separated from the base (or target) URL by a question mark. If there were additional parameters, they would be separated by an ampersand (&). The syntax for using parameters in a URL is as follows:

http://targetURL ? parm1name=parm1value & parm2name=parm2value & parm3name=parm3value etc...

The collection of parameters in an URL is also known as the query string, and can be retrieved with the QueryString collection of the Request object:

If Request.QueryString("id") = "" Then Response.Write "No ID entered!"

As with the Request.Form example in Listing 31.4, the value passed to an ASP page in the query string can be retrieved and used in a database query:

   sSQL = "SELECT Title FROM [Title Author], [Titles] "
   sSQL = sSQL & " WHERE [Title Author].ISBN = [Titles].ISBN "
   sSQL = sSQL & " and [Title Author].AU_ID=" & Request.QueryString("id")

As an exercise, create AUTHOR.ASP using the preceding query. Except for the database field names, the structure of the ASP file should be identical to that in Listing 31.4.

Updating Information in a Database

Although displaying data with ASP is useful, at some point you also need to add or edit information. The previous section described two ways to get input from a client's browser to an ASP page:

  • Posting with HTML forms

  • Adding parameters to the URL querystring

Both of these methods are useful and appropriate in certain cases, but using the POST method with HTML forms is much more versatile. In the examples shown so far, you have used only the TEXT input field. However, there are many types of HTML form elements that can be used, such as radio buttons, drop-down boxes, and free-form text areas. One type of field that is very useful when dealing with database updates is a hidden form field. A hidden form field is like a text field, but the user cannot see it or change its value. This type of field can be generated from an ASP page and sent down to the browser. When the user submits a form, the value of a hidden form field is sent back to the server with the other form fields.

Revisit the example in Listings 31.3 and 31.4, and add edit capability for the author's name and birth year. In addition, you will consolidate all of the functionality from the previous example into subroutines in a single ASP page:

  • AskForAuthors takes the place of DBQUERY.HTM.

  • GetAuthorList replaces DBSEARCH.ASP.

  • DisplayEditScreen, a new procedure, displays a form that allows you to edit an author's information.

  • UpdateDBInfo changes the database.

The code for the new ASP page, AUTHOREDIT.ASP, is shown in Listing 31.5.

Listing 31.5  ASP Page Allowing Searching and Editing

Dim cn
Dim rs
Dim sSQL
Const MYASPNAME="authoredit.asp"

Sub AskForAuthors()

   Response.Write ("<H1>Biblio Database Search</H1><HR>")
   Response.Write ("<FORM ACTION=" & MYASPNAME & "?mode=search METHOD=POST>")
   Response.Write ("Enter Author to search for:")
   Response.Write ("<INPUT TYPE=TEXT NAME=txtSearch>")
   Response.Write ("<INPUT TYPE=SUBMIT VALUE=""Click to Search"">")
   Response.Write ("</FORM>")

End Sub

Sub GetAuthorList()

   Set cn = Server.CreateObject("ADODB.Connection")
        cn.Open "DSN=BIBLIO"

   sSQL = sSQL & "'" & Request.Form("txtSearch")
   Set rs = cn.Execute(sSQL)

   Response.Write("<TABLE BORDER=1><TR>Author's Name</TR>")
   While Not rs.EOF
      Response.Write ("<TR><TD><A HREF=" & MYASPNAME & "?id=")
      Response.Write rs.fields("AU_ID") & "&mode=dispedit>"
      Response.Write rs.Fields("Author")
      Response.Write ("</A><TD></TR>")


End Sub

Sub DisplayEditScreen()

   Set cn = Server.CreateObject("ADODB.Connection")
        cn.Open "DSN=BIBLIO"

   sSQL = "SELECT * FROM AUTHORS WHERE AU_ID= " & Request.QueryString("id")
   Set rs = cn.Execute(sSQL)

   Response.Write ("<H1>Edit Author Information</H1><HR>")
   Response.Write ("<FORM ACTION=" & MYASPNAME & "?mode=updatedata METHOD=POST>")

   Response.Write ("Name:<INPUT TYPE=TEXT NAME=txtName")
   Response.Write (" VALUE='" & rs.Fields("Author") & "'><BR>")
   Response.Write ("Year Born:<INPUT TYPE=TEXT NAME=txtYear")
   Response.Write (" VALUE='" & rs.Fields("Year Born") & "'><BR>")
   Response.Write ("<INPUT TYPE=HIDDEN NAME=AuthorID VALUE=")
   Response.Write (rs.Fields("AU_ID") & ">")

   Response.Write ("<INPUT TYPE=SUBMIT VALUE=""Update Info"">")
   Response.Write ("</FORM>")

End Sub

Sub UpdateDBInfo()

   Set cn = Server.CreateObject("ADODB.Connection")
        cn.Open "DSN=BIBLIO"

   sSQL = "UPDATE AUTHORS SET Author='" & Request.Form("txtName") & "',"
   sSQL = sSQL & "[Year Born]=" & Request.Form("txtYear")
   sSQL = sSQL & " WHERE AU_ID=" & Request.Form("AuthorID")

   Response.Write ("<H1> Information Updated!</H1>")
End Sub

Select Case Request.QueryString("mode")
   Case "search"
   Case "dispedit"
   Case "updatedata"
   Case Else
End Select

Set rs = Nothing
Set cn = Nothing


When working with user input, be wary of the quote character. You might need to write a function to manipulate quotes in a form field before using the field value in an SQL statement.

Listing 31.5 is a single ASP file, yet it generates four distinct HTML screens. The query string parameter mode determines what action the ASP page performs.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020