There are many different potential sources for data. Earlier, we used data that resides in a plain text file. Frequently, data is kept in an online database. Several DSOs such as RDS and JDBC can access these directly. You can also use many server-side technologies to access data. Active Server Pages technology (part of Microsoft Windows NT Server_Internet Information Services) supports directly connecting to databases, such as Microsoft SQL Server. Code Listing 20-7 contains an example of such a page. Note that this page will not work directly from the CD. It must be run on a properly configured server.
Code Listing 20-7.
<%@ LANGUAGE="JScript"%> <HTML> <HEAD> <TITLE>Code Listing 20-7</TITLE> <% Conn = Server.CreateObject("ADODB.Connection") Conn.Open("DSN", "id", "password") rsFiles=Conn.execute("SELECT FName, LName FROM NameTbl WHERE Reg=1") rsFiles.MoveFirst() %> </HEAD> <BODY> <TABLE BORDER="1"> <THEAD> <TR><TD>First Name</TD><TD>Last Name</TD></TR> </THEAD> <% while (!rsFiles.EOF){ %> <TR><TD><%=rsFiles(0)%></TD><TD><%=rsFiles(1)%></TD></TR> <% rsFiles.MoveNext() } Conn.Close() %> </TABLE> </BODY> </HTML> |
Much of the content in Code Listing 20-7 is beyond the scope of this book; however, here is a quick rundown of what it does: Active Server Pages allows you to mix server-side script into a client-side Web page. The <% and %> characters are one way to signify the beginning and end of a server-side script block. The first line of server-side script notifies the server that the ASP page uses JScript. The next server-side script block creates a connection object and opens a connection to a database, where DSN signifies the Data Source Name of the database (found in the Control Panel for ODBC on the server), id is the desired user, and password is the password used to access the database. The rsFiles recordset is created from a standard SQL query against the database, asking for the FName and LName fields of all the records in the NameTbl table for which the Reg field is set to 1. The recordset is then set to the first record.
The beginning of a table is written to the client-side page, and then the next block of server-side script begins. This loops through all the records in the recordset, writing a line of HTML to the page that consists of a table row with the contents of the first and second fields of the current record, each in their own cell. The syntax <%=variableName%> will write the content of variableName to the HTML page. When the loop finishes, the connection to the database is closed to reduce the load on the server. Finally the table and the rest of the Web page are closed. This ASP page will return a table of first and last names from a database.