Sie sind auf Seite 1von 17

Boston University School of Management IS465 Managing Data Resources Spring 2002 ASP and SQL Server 2000

1. What do you need to get started? Basic knowledge of HTML including: - Creating simple HTML documents and understanding the tags, especially tags for tables - Creating simple forms (all of the examples covered in class will use forms for entering, displaying data). Access to the Teaching server and a directory to hold your files (.html, .asp). Based on your earlier class, you should have these in place. Please test to make sure that your login account is still valid and that your directory is still accessible to you for read, write, and execute of files. Access to a SQL Server account on the teaching server.

2. The Structure or Setup We will be simulating a Client / Server set up where the teaching server machine is going to act both as the server and as the client. The teaching server performs the roles of 2 servers in our specific situation: it hosts the web and hence acts as the web server, and it hosts the database and hence acts as the data server. As a web server, it runs the Internet Information Service (IIS). The IIS is now responsible for providing us with the constructs we need to access the SQL server database and more importantly, to work with ASP. The Active Server Pages (ASP) is an extension of the web server (IIS) that allows you to do server-side scripting. At the same time, it also provides you with a compendium of objects and components that manage the interaction between the web server and your browser. These objects can be manipulated by scripting languages. We will be using VBScript as the scripting language for illustrating access to the SQL server with ASP. ASP supports six Active Server Objects: - Request Object deals with application or user requests made to web applications - Response Object deals with the responses from the server to the client requests - Server Objects the most important of all 6. Deals with several commonly used functions like converting text to HTML or URL. ActiveX Data Objects (ADO) used to access and manipulate the SQL server database is a part of the Server object. - Application Object used to manage the different applications that are running against the server - Session Object used to manage the different sessions within each applications - ObjectContext used with Microsoft Transaction Server (not of much concern to us now) ODBC Open Database Connectivity An interface that will allow you to view the data held in different types of databases including SQL server. It is a standard created by Microsoft in 1992 that allows you to add ODBC statements to programs

so that the program may access and manipulate data in databases. ODBC drivers are software modules that permit access to the different databases. The ODBC interface (or standard) allows users to access from one database, data stored in another database of a different type. What if you want to access data that is not stored in a conventional (relational or Access) database? The answer is the OLE-DB. OLE-DB In 1997, Microsoft provided another easier specification for an interface called OLE-DB and tried very hard to make sure that it is faster and easier to use than ODBC. The OLE-DB allows a program to access information in any type of data store (databases, or other files like email folders, spreadsheets, graphs etc.). Eventually, OLE-DB may replace ODBC completely. For now, it sits on top of the ODBC drivers and allows you to use existing ODBC drivers. The OLE-DB equivalent of an ODBC driver is called a PROVIDER. A good definition of a PROVIDER is something that provides data! PROVIDERS are NOT THE SAME as DRIVERS. There are many more drivers available than there are PROVIDERS. So if you need to access information from a database, you will have to use a PROVIDER and a DRIVER together. The good news is most of the work is done by the PROVIDER and so you do not have to know a great deal (in fact nothing) about the DRIVER used for accessing a database. Microsoft SQL Server is one such database where the PROVIDER will take care of everything and you dont need the ODBC driver. OLE-DB PROVIDER is not available (yet) for ORACLE, SYBASE and other databases and hence you still need to use ODBC drivers for these databases. Can you tell me why we need to know the above? We will be using an OLE-DB PROVIDER for accessing the SQL Server. This has some advantages that are described later in this document.

3. ActiveX Data Objects (ADO) There are three important ADO objects we need to be familiar with in our class. The Connection Object The Command Object The Recordset Object The Connection Object is used to connect to the database. Once a connection is established, the object may be re-used any number of times as you want in your program code. The other two objects (Command and Recordset) are both sublcasses of the Connection Object. Hence you do not always need a Connection object to connect to the database as each of the other two can connect to the database as well. The Command Object is used to define and run the SQL commands against the database. These commands are NOT IN ASP but in the language you know as SQL. The commands are typically used to return information from a database but can also be used to insert, update, and delete information from a database. The Recordset Object is the most used of all three. It is used to hold information that is retrieved from the databases (the records) and we need to be very careful about how these objects are created and used. The Recordset object can be used to view and alter the databases. It is used to find specific records, move through the database one record at a time, delete records, restrict access to sensitive information from specific users, sort records, and update one or more of the existing records.

4. Type of Connections to the SQL Server Database There are two types of connections that we will discuss in this document. The first type requires the creation of a DSN, which is an ODBC data source for a specific database. The systems administrator of the server is responsible for setting up the DSN on that server. If DSN is used, then as mentioned in part 3 above, the Command and Recordset Objects can directly be used to connect to the server and you dont really need the Connection object. What if you are unable to set up the DSN? The answer is a DSN-less connection. The DSN-less connection requires the use of the Connection object to connect to the database. The Command and Recordset objects will be used to do the specific purpose each was designed to do and will not be used to connect to the database. You will see a detailed example below that illustrates the use of all of these objects and the use of HTML forms and tags. 5. Example 1: The following is an example of a form that would allow you to type in your query in a form window and retrieve and display the results in another page. The results will be displayed by formatting the data into a HTML table. Input Form (sqlcommand.html)
1. 2. 3. 4. 5. 6. 7. 8. <HTML> <HEAD> <TITLE> SQL Entry Form </TITLE> </HEAD> <BODY> <h1 align="Center">ENTER SQL BELOW </h1> <FORM id="Sqlform" name="Sqlform" action="runsql.asp" method="post"> <center><p><TEXTAREA id="Sqltext" name="Sqltext" Cols=40 Rows=4></TEXTAREA><br> 9. <center><p><INPUT id="Submit" name="Submit" type="submit" value="Run"> 10. <input id="Reset" name="Reset" type="reset" value="Reset"></p> 11. </center> 12. </form> 13. </body> 14. </html>

Explanation: The above HTML code creates a form (line 7) with a text area in which uses may enter SQL codes (line 8), a submit button that executes the SQL statements (line 9) and a reset button that clears the text area (line 10). Notice that the action associated with the form in line 7 is the execution of an asp code file runsql.asp, as indicated by the phrase action=runsql.asp and that the method used to send the user input is POST, as indicated by the phrase method=post. Another way to send data is by GET method. While GET method appends the query string to the end of a URL (in this case, runsql.asp), POST method buries the information inside the HTTP header. Screen snapshot:

The Executable ASP file (runsql.asp)


1. 2. 3. 4. 5. 6. 7. 8. <%@ Language=VBScript %> <HTML> <HEAD> <TITLE> SQL Results </TITLE> </HEAD> <BODY> <% Dim objRS, objConn

9. set objConn = Server.CreateObject("ADODB.Connection") 10. If cstr(Request.Form ("Sqltext") ) = "" Then 11. Response.Write ("<Center><h2>Warning: Please enter a query to run </h2></Center>") 12. Else 13. objConn.Open "PROVIDER=MSDASQL;DRIVER={SQL Server};SERVER=TEACHSERV;DATABASE=pubs;UID=xxxx;PWD=xxxx" 14. set objRS=objConn.Execute(cstr(Request.Form("Sqltext")), intRecordsAffected) 15. If intRecordsAffected = -1 Then 16. objRS.MoveFirst 17. %> 18. <Center><h2>SQL RESULTS </h2> 19. <b>SQL Statement:</b><%= cstr(Request.Form("Sqltext")) %> 20. <p> 21. <TABLE BORDER=1 COLS=<%=objRS.Fields.Count %>> 22. <TR> 23. <% For Each objField in objRS.Fields %> 24. <TH> <%= objField.Name %> </TH> 25. <% Next %> 26. </TR> 27. <% Do While Not objRS.EOF %> 28. <TR> 29. <% For Each objField in objRS.Fields %> 30. <TD align=left>

31. <% If IsNull(objField) Then 32. Response.Write ("&nbsp;") 33. Else 34. Response.Write (objField.Value) 35. End If 36. %> 37. </TD> 38. <% Next 39. objRS.MoveNext %> 40. </TR> 41. <% Loop %> 42. </TABLE> 43. <% objRS.close 44. set objRS=Nothing 45. End If 46. objConn.close 47. Response.Write "<p>" 48. Response.Write intRecordsAffected & " records affected <P>" 49. End If 50. Response.Write ("<p> Return to <a href=sqlcommand.html> SQL Entry Form </a>") 51. set objConn=Nothing 52. %> 53. </center> 54. </body> 55. </html>

Explanation: The above HTML code connects to the database in use (line 10, 11), retrieve the desired information (line 16, 17) with the command provided by the user (line 17), and presents the result to the user in a table (line 23 to 47). The following line-by-line explanation will show in more details how the scripts manage to do so.
1. <%@ Language=VBScript %>

We learned earlier that ASP uses server-side scripting. Here we see that server-side scripts is inserted in an ASP file between<% and %> delimiters. It is this server-side script that enables us to generate HTML document dynamically. When an ASP file is executed on the server, the script gets executed and the results are reflected in the resulted HTML document. We will see this point more clearly later. Line 1 tells the server that the language under use is VBScript. Note the @ character right after the <% delimiter.
2. 3. 4. 5. 6. <HTML> <HEAD> <TITLE> SQL Results </TITLE> </HEAD> <BODY>

These are standard HTML statements. It tells that this file is in <HTML> format and the title of the page is SQL results.
7. <% 8. Dim objRS, objConn 9. set objConn = Server.CreateObject("ADODB.Connection")

Line 7 indicates start of server-side scripts. Line 8 declares two variables, objRS and objConn. Unlike in C or C++, in VBScript, variables are declared without specifying their types. To assign an object to a variable, set command is used as in line 9 and line 10. In line 9, a connection object is created and assigned to objConn. Note that so far we have connected neither objRS nor objConn to any database yet.
10. If cstr(Request.Form ("Sqltext") ) = "" Then 11. Response.Write ("<Center><h2>Warning: Please enter a query to run </h2></Center>") 12. Else

There are two things worth attention in this code fragment. First is the Request object. As we already know, Request object deals with application or user requests, both input and outpout. In line 11, with the help of Form collection, we retrieve data contained in Sqltext sent by user (Line 7 of input form (sqlcommand.html). Note the phrase method=post). If GET method is used to send data, we have to use QueryString collection instead (You may ask what a collection is. Well, just consider it as a set of values or objects that is retrievable by referring to their names. So Request.Form (Sqltext) will return the value contained in Sqltext). CStr() is the function that converts the parameter to a string. Therefore, line 11 examines if the user has inputted something. In line 12, Response object calls its Write method (in the same way as a C++ object calls its member function) to write a string to the HTML document which is being generated. It is in this simple operation that we dynamically generates a HTML document: the content in the HTML document depends on whether the user provided a command or not. Second we see the familiar If Else combination here. In VBScript, flow control is done in a similar way as in C++. The difference lies mostly in the syntax rather than in the semantics. For example, in VBScript, If Then Else Else If is used to run various blocks of code depending on conditions. Dont forget the Then in the If phrase (line 11) and you provide an End If to signal the end of the block rather than using a closing }. Notice the matching End If is way behind in line 49. We will explain other flow controls when they are used in the codes. So this fragment judges if user has inputted a command, if not, an error message is displayed. If yes, we try to establish a connection with the database in use with line 14 and 15:
13. objConn.Open "PROVIDER=MSDASQL;DRIVER={SQL Server};SERVER=TEACHSERV;DATABASE=pubs;UID=XXXX;PWD=XXXX"

Declared in line 8 and assigned in line 10, Connection object objConn was connected to database here in line 14. The general form of the Open method for the connection object is: Connection.Open ConnectionString The ConnectionString parameter is a string that specifies a data source either as a data source name (DSN), or by specifying a detailed connection string made up of individual parameter=value arguments separated by semicolons, and containing no spaces(DSNless connections discussed earlier). You probably can tell that we are using DSN-less

connection here. In our example, we are telling the server that database to be connected is a pubs on the teaching server, whose name is TEACHSERV. The provider for the database is MSDASQL and the driver is {SQL Server}. We also provide the user information in UID= and PWD= phrase. In your own code, you have to replace the XXXX with your own user information. Having established the connection with the database, we now try to retrieve the data we need and store it somewhere we can access:
14. set objRS=objConn.Execute(cstr(Request.Form("Sqltext")), intRecordsAffected)

By asking objConn to execute the commend inputted by the user, we try to put the data retrieved from the command in a Recordset object objRS. Later, we can access the data by referring to objRS. The second augment in calling Execute(), intRecordsAffected, holds the number of records that is changed after the command is executed. Notice that a negative value in intRecordsAffected suggests no record is changed but the Recordset is not empty and a 0 value suggests an empty Recordset.
15. If intRecordsAffected <> 0 Then 16. objRS.MoveFirst 17. %>

In line 15, the value of intRecordsAffected is used to judge whether the Recordset, objRS, is empty or not. If yes, we move to the first record in the Recordset. Line 17 ends this portion of server-side scripts. So far, we have retrieved the user command, established connection with the database and fetched the data to the Recordset object objRS. The next step is to present it to the user in a nice way. In this example, we want to present the data is a tabular format, which is done by line 20-43.
18. 19. 20. <Center><h2>SQL RESULTS </h2> <b>SQL Statement:</b><%= cstr(Request.Form("Sqltext")) %> <p>

Line 18-20 put the title of the table and the command used in the center of the browser winder. There is a shot script <%= cstr(Request.Form("Sqltext")) %> embedded in line 19. This script means to put here the value of the Sqltext. When the server runs this script, the value of Sqltext takes the place of this script in the resulted HTML document. Dont forget the = before the cstr(). Line 21 to line 41 describes how to generate the table. We want the head of the table to display the names of the columns, and then each row in the Recordset objRS takes a row in the table.
21. 22. 23. <% 24. 25. <% 26. <TABLE BORDER=1 COLS=<%=objRS.Fields.Count %>> <TR> For Each objField in objRS.Fields %> <TH> <%= objField.Name %> </TH> Next %> </TR>

Line 21 defines the table. The field information in Recordset is stored in Fields collection, whose propery Count indicates the number of fields in a Recordset. In the generated HTML document, the actual number of fields in the Recordset will replace the embedded script <%=objRS.Fields.Count %>. After the table is defined, we want to fill content into the table. HTML use tag pair <TR>, </TR> to indicate the start and end of a row and <TH> and </TH> to indicated the start and end of a head. The For Each Next loop from line 23 25 repeated fill the name of each field into the table head. You can interpret line 23 as For each field in the Recordset objRS. Note that objRS.Fields is a collection of Field object, and objField is an variable name by which we refer to the individual object in the objRS.Fields collection. Also note line 24. First, in the resulted HTML document, the embedded script will be replaced by actual field name. Second, by putting <TH> and </TH> block in the For Each Next loop, the server put it into the resulted HTML document each time the loop is executed. This point can be seen more clearly when we compare the source code of the resulted HTML document with the ASP source code. Now that the table head is done, we can put the content in the Recordset into the table.
27. <% 28. 29. <% 30. 31. <% 32. 33. 34. 35. 36. %> 37. 38. <% 39. 40. 41. <% 42. Do While Not objRS.EOF %> <TR> For Each objField in objRS.Fields %> <TD align=left> If IsNull(objField) Then Response.Write ("&nbsp;") Else Response.Write (objField.Value) End If </TD> Next objRS.MoveNext %> </TR> Loop %> </TABLE>

This Do While Loop block, functioning like While-loop in C++, enable us to turn to each record in a Recordset. When a non-empty Recordset is opened, the system automatically set the first record as the current record. You can navigate the Recordset with certain commands such as MoveFirst, MoveLast, MoveNext and MovePrevious. Here we use MoveNext to move to next record after we finish with the current record. The loop condition is tested by the return value of EOF method, which returns TRUE when we move out of the last record in the Recordset. The <TR> and </TR> pair in line 28 and line 40 defines the beginning and ending of a row in the table. Again that they are nested in the Do While Loop block suggests each time the loop iterates, they will be put into the resulted HTML document. Similar to how the table head was defined, the cells in a row is defined inside a For Each Next loop. The table ends after every record in the Recordset is taken care of after the Do While Loop block.

In this code fragment, the ASP scripts and HTML tags are heavily mixed. You should pay a lot of attention to make sure that the every bit of ASP scripts is enclosed within the <% %> delimiters. Now that we have finished with the database, we should close the Recordset (line 43) and the connection (line 46), and release all the resources occupied by the two objects (line 44 and line 51) (Just the same as you do to the files opened and memory dynamically allocated to the pointers when you are done with them in C++). Line 47 and line 48 displays the number of records affected in the browser window and line 50 adds a hyperlink to the command input page.
43. <% objRS.close 44. set objRS=Nothing 45. End If 46. objConn.close 47. Response.Write "<p>" 48. Response.Write intRecordsAffected & " records affected <P>" 49. End If 50. Response.Write ("<p> Return to <a href=sqlcommand.html> SQL Entry Form </a>") 51. set objConn=Nothing 52. %> 56. </center> 57. </body> 58. </html>

Line 56 to 58 closes the HTML documents with some tags. Screen snapshot:

6. Example 2 This example allows users to retrieve detailed author information by last name. It consists of two ASP pages: the first ASP page generates a list of all authors last names and allows user to choose author by last name. The second ASP accepts user choice and displays detailed information of the authors who have the chosen last name. Input Form (authorQueryFrom.asp)
1. <%@ Language=VBScript %> 2. <HEAD><TITLE> Query Form with Pull-down list using ASP and SQL Server </TITLE></HEAD> 3. <BODY> 4. <% 5. Dim RS 6. Set RS=Server.CreateObject("ADODB.Recordset") 7. RS.open "Select au_lname from authors order by 1","PROVIDER=MSDASQL;DRIVER={SQL Server};SERVER=TEACHSERV;DATABASE=pubs;UID=XXXX;PWD=XXXX" 8. RS.MoveFirst 9. %> 10. <FORM METHOD="get" ACTION="AuthorQuery.asp"> 11. <H2>Select a last name from the list below to <br> 12. obtain detailed information about that author(s)</H2><P> 13. <P> 14. <SELECT NAME="aulnamelist" SIZE="1"> 15. <% 16. Do While NOT RS.EOF 17. Response.Write "<OPTION VALUE='" & RS("au_lname") & "'>" 18. Response.Write RS("au_lname") & "</OPTION>" 19. RS.MoveNext 20. Loop 21. RS.Close 22. Set RS=Nothing 23. %> 24. </SELECT></P> 25. <P><INPUT ID="Submit" NAME="Submit" TYPE="Submit" VALUE="Get Author Details"> 26. <INPUT ID="Reset" NAME="Reset Values" TYPE="Reset" VALUE="Reset"></P> 27. </FORM> 28. </BODY> 29. </HTML>

Explanation: The above HTML code creates a form (line 10) with a list of last names from which uses can select (line 14), a submit button that sends the user choice (line 25) and a reset button that resets the user choice (line 26). Notice that the action associated with the form in line 10 is the execution of an asp code file AuthorQuery.asp, as indicated by the phrase action=AuthorQuery.asp and that the method used to send the user input is GET, not the POST method in example 1. Again GET method appends the query string to the end of a URL (in this case, AuthorQuery.asp). The first ASP script fragment, line 4 to 9, establishes the connection to the database directly through a Recordset object, RS. Recall that in Example 1, we first open a Connection object and then set the Recordset object with

Execute method of the Connection object. Here we achieve the same goal by calling the open method of Recordset object. The general form for Open method of Recordset is: Recordset.Open Source, ActiveConnection, CursorType, LockType, Options In the example, the Open method takes first two parameters: the first one is the SQL command that is used to retrieve the qualified data from the database, and the second is the connection string. Notice that the string is exactly the same as the one we used in Example 1 to open the Connection object (Line 13). The second ASP script fragment, Line 15 to 23, fills the list with the last names retrieved from the database. Pay attention to how Response.write put HTML tags and each individual last name to form the description on the list options. Screen Snapshot

Handling Page (authorQueryFrom.asp)


1. 2. 3. 4. 5. <%@ Language=VBScript %> <HEAD><TITLE>Author Query Result</TITLE></HEAD> <BODY> <% Dim sqlstmt, lname, connStr

6. Sub MakeTable (SourceIn, connStr) 7. Dim RS 8. Dim objField 9. Set RS=Server.CreateObject("ADODB.Recordset") 10. RS.Open SourceIn, connStr

11. RS.MoveFirst 12. Response.Write "<FONT Color=RED>The SQL Statement Executed is: " 13. Response.Write SourceIn 14. Response.Write "</FONT><p>" 15. Response.Write "<TABLE BORDER=1><TR>" 16. For each objField in RS.Fields 17. Response.Write "<TH>" & objField.Name & "</TH>" 18. Next 19. Do while NOT RS.EOF 20. Response.Write "<TR>" 21. For Each objField in RS.Fields 22. Response.Write "<TD>" 23. If IsNull (objField.value) Then 24. Response.Write "&nbsp" 25. Else 26. Response.Write objField.value 27. End If 28. Response.Write "</TD>" 29. Next 30. RS.MoveNext 31. Response.Write "</TR>" 32. Loop 33. Response.Write "</TABLE>" 34. RS.Close 35. Set RS = Nothing 36. End Sub 37. lname = Request.QueryString("aulnamelist") 38. Response.Write "The last name selected is " & lname & "<p>" 39. sqlstmt = "Select * from authors where au_lname='" & lname & "'" 40. connStr = "PROVIDER=MSDASQL;DRIVER={SQL Server};SERVER=TEACHSERV;DATABASE=pubs;UID=XXXX;PWD=XXXX" 41. call MakeTable (sqlstmt, connStr) 42. %> 43. </BODY> 44. </HTML>

Explanation: In this file, building of table and filling the table are done in a user defined subroutine, called MakeTable(line 6 to line 36). The command string was retrieved in line 37, with the help from QueryString collection from Request object. Line 39 construct the SQL command to be used. Notice how a string constant is formed (with character on both side of lname). Subroutine MakeTable takes the SQL command and the connection string as the parameters. In the subroutine, line 7 and line 8 declare two variables: RS and objField. Line 9 initiates the Recordset object RS and the connection to database is established in line 10. Line 12 to 14 displays the SQL command in red color. Table is defined in line 15 to line 33. Line 16 to 18 defines the head and the rows are filled in with a nested loop: Do WHILE LOOP (Line 19 to 32) loop for each record (row) and For ... Next loop for each field (line 21 to 29).

Screen snapshot: note the hightlighted part in the address bar. Thats where data are sent with GET method.

7. Example 3 This example shows an online survey on students background and their knowledge about programming and DBMS. Once student submits the survey, the answer is send to the server and stored in a table, which already has the students ID. If the students ID cant be found, a new entry should be created for the user. Input Form (preclass-survey.html)
1. <html> 2. <head> 3. <title>IS999&nbsp; Pre-class Survey</title> 4. </head> 5. <body> 6. <h1 align="center">Welcome to IS999 A9, Winter 2001</h1> 7. <p>The only purpose of this short survey is to give me some more ideas about who you are and what you already know. Your input will help me better prepare the course for you. I will keep your answer to myself and will only use it in aggregation. The student ID information you input will only be used for making sure that each of you has only one entry in the database.</p> 8. <form method="POST" action="survey.asp"> 9. <p>1. Student ID: <input type="text" name="Sid" size="14" tabindex="1" maxlength="11">(in 10. the format of U99-99-9999, please)</p> 11. <p>2. Have you ever programmed with the following programming language?</p> 12. <table border="0" width="680"> 13. <tr> 14. <td align="right" width="208">C or C++:</td> 15. <td width="458"> 16. <input type="radio" value="1" name="C">Never&nbsp;&nbsp;&nbsp; 17. <input type="radio" name="C" value="2">A bit&nbsp;&nbsp;&nbsp;

18. <input type="radio" name="C" value="3">A lot&nbsp;&nbsp; 19. <input type="radio" name="C" value="4">I am a master 20. </td> 21. </tr> 22. <tr> 23. <td align="right" width="208">VB or VBScript:</td> 24. <td width="458"> 25. <input type="radio" value="1" name="VB">Never&nbsp;&nbsp;&nbsp; 26. <input type="radio" name="VB" value="2">A bit&nbsp;&nbsp;&nbsp; 27. <input type="radio" name="VB" value="3">A lot&nbsp;&nbsp; 28. <input type="radio" name="VB" value="4">I am a master 29. </td> 30. </tr> 31. <tr> 32. <td width="208" align="right">Java or JavaScript:</td> 33. <td width="458"> 34. <input type="radio" value="1" name="Java">Never&nbsp;&nbsp;&nbsp; 35. <input type="radio" name="Java" value="2">A bit&nbsp;&nbsp;&nbsp; 36. <input type="radio" name="Java" value="3">A lot&nbsp;&nbsp; 37. <input type="radio" name="Java" value="4">I am a master 38. </td> 39. </tr> 40. <tr> 41. <td width="208" align="right">ASP or other Online DB tools:</td> 42. <td width="458"> 43. <input type="radio" value="1" name="ASP">Never&nbsp;&nbsp;&nbsp; 44. <input type="radio" name="ASP" value="2">A bit&nbsp;&nbsp;&nbsp; 45. <input type="radio" name="ASP" value="3">A lot&nbsp;&nbsp; 46. <input type="radio" name="ASP" value="4">I am a master 47. </td> 48. </tr> 49. </table> 50. <p>3. Have you taken IS465, Managing Data Resources?&nbsp;&nbsp;&nbsp;&nbsp; 51. <input type="radio" name="IS465" value="N">No&nbsp;&nbsp; 52. <input type="radio" name="IS465" value="Y">Yes&nbsp;&nbsp; 53. </p> 54. <p>4. Have you taken IS482, Working in the Knowledge Economy?&nbsp;&nbsp;&nbsp;&nbsp; 55. <input type="radio" name="IS482" value="N">No&nbsp;&nbsp; 56. <input type="radio" name="IS482" value="Y">Yes&nbsp;&nbsp; 57. </p> 58. <p>5. Are you an international student?&nbsp;&nbsp;&nbsp; 59. <input type="radio" name="INTL" value="N">No 60. <input type="radio" name="INTL" value="Y">Yes&nbsp; (if yes, the country you are from: 61. <input type="text" name="Country" size="27">)</p> 62. <p>6. Any comment or concern regarding the course? Write it down:</p> 63. <blockquote> 64. <p align="center"><textarea rows="4" name="Comment" cols="52"></textarea></p> 65. </blockquote> 66. <p align="center"><input type="submit" value="Submit" name="B1">&nbsp;&nbsp; 67. <input type="reset" value="Reset" name="B2"></p> 68. </form> 69. </body> 70. </html>

Explanation: The logic in the source code is the same as that in the input form for example 1. Note that you can improve the form by adding scripts to check the validity of the inputted value for each field, for example, you can check if the Student ID is in the right format or not before submitting it to the server. Handling Page(survey.asp)
1. <%@ LANGUAGE="VBSCript" %> 2. <% Response.Buffer = True %> 3. <html> 4. <head> 5. <meta http-equiv="Content-Language" content="en-us"> 6. <meta http-equiv="Content-Type" content="text/html; charset=windows1252"> 7. <title>Thank you</title> 8. </head> 9. <body> 10. <h1 align="center">Welcome to IS999 A9, Winter 2001</h1> 11. <p> 12. <% 13. sID = cstr(Request.Form("Sid")) 14. If sID = "" Then 15. Response.Write "You have to tell me your student ID, please go back to the survey page by using BACK button of your browser and try again." 16. Response.End 17. End If 18. Dim objRS 19. set objRS = Server.CreateObject("ADODB.Recordset") 20. strConn = "PROVIDER=MSDASQL;DRIVER={SQL Server};SERVER=TEACHSERV;DATABASE=pubs;UID=XXXX;PWD=XXXX" 21. sql = "SELECT * FROM IS467A1 WHERE SID='" + sID + "'" 22. objRS.Open sql, strConn, 2, 2 23. If objRS.BOF Then 24. Response.Write "Thanks for filling the survey and see you in class!" 25. objRS.AddNew 26. objRS("SID") = Request.Form("Sid") 27. Else 28. Response.Write trim(cstr(objRS("FName"))) 29. Response.Write ", thanks for filling the survey and see you in class!" 30. End If 31. objRS("C") = Request.Form("C") 32. objRS("VB") = Request.Form("VB") 33. objRS("JAVA") = Request.Form("Java") 34. objRS("IS465") = Request.Form("IS465") 35. objRS("IS482") = Request.Form("IS482") 36. objRS("INTL") = Request.Form("INTL") 37. objRS("Country") = Request.Form("Country") 38. objRS("Comment") = Request.Form("Comment") 39. objRS.Update 40. objRS.Close

41. set objRS=NOTHING 42. %> 43. </p> 44. <p>Your name<BR> 45. <% =date %></p> 46. </body> 47. </html>

Explaination: Line 2 asks server to put responses in a buffer first before send it to the client browser. One good thing of doing so is that you can end the response when you find something is wrong, for example, when you find out the SID is empty (Line 14), you can write an error message (line 15) and then end the response buy calling the End method of Response object (line 16).
18. Dim objRS 19. set objRS = Server.CreateObject("ADODB.Recordset") 20. strConn = "PROVIDER=MSDASQL;DRIVER={SQL Server};SERVER=TEACHSERV;DATABASE=pubs;UID=XXXX;PWD=XXXX" 21. sql = "SELECT * FROM IS467A1 WHERE SID='" + sID + "'" 22. objRS.Open sql, strConn, 2, 2

Line 20 assigns a connection string and note that it is exactly the same as we used in example 1 and 2. Line 21 assigns a SQL command string. Dont forget the s around the sID. Line 22 opens the recordset. Recall that the general form of Open method is: Recordset.Open Source, ActiveConnection, CursorType, LockType, Options We have explained Source and ActiveConnection before. CursorType is the parameter that decides whether you can make change to the recordset and how you can navigate in the recordset. Here we pass a 2, which stands for dynamic cursor. Dynamic cursor supports forward and backward navigation and allows you to make change to the records. When multiple users are updating the same database, somebody else may happen to overwrite the modification you just made to the database. (You will learn more on this down the road.) Locking is one mechanism that prevents such accident from happening. Here we use type 2 lock: pessimistic lock which locks the entire record when we first start editing a record.
23. If objRS.BOF Then 24. Response.Write "Thanks for filling the survey and see you in class!" 25. objRS.AddNew 26. Else 27. Response.Write trim(cstr(objRS("FName"))) 28. Response.Write ", thanks for filling the survey and see you in class!" 29. End If

Line 23 uses BOF function of recordset to test if the recordset is empty of not. If it is empty, the server will set the BOF to true upon opening it. Therefore, if it is empty, the SID cannot be found in the database and we have to create a new

entry for it using AddNew (Line 25). Otherwise, the server will set the first record as current record. Line 31 to 38 updates the current record. Note how we access to a particular field with the field name: by putting the field name in the ()s. To make the new values actually get in the database, line 39 calls the Update command to commit the change. 8. Several tips Remember you are writing VBScripts and not C++ program: there is no ; after each sentences; in most cases, you cannot bring a line of code into several lines; the equal to operator is a single = not ==; the not equal to operator is <> not !=; and finally, there are commands that dont need parameters and () as well (for example, there is no () after BOF in Line 23 in example 3). Make sure the field name in your ASP codes are spelled exactly the same as that in the database Put every bit of scripts in <% %> delimiters Be extremely careful when you are constructing a SQL command. It is recommended that you try the SQL first before put it into ASP codes. To find if the constructed SQL command is correct or not, you can always put it into the response and check it in the browser:
sql = "SELECT * FROM IS467A1 WHERE SID='" + sID + "'" Response.Write sql

Das könnte Ihnen auch gefallen