+ All Categories
Home > Documents > ASP and SQLServer Tutorial

ASP and SQLServer Tutorial

Date post: 05-Apr-2018
Category:
Upload: soter-macbarthos
View: 227 times
Download: 0 times
Share this document with a friend
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 di fferent se ssions 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
Transcript
Page 1: ASP and SQLServer Tutorial

8/2/2019 ASP and SQLServer Tutorial

http://slidepdf.com/reader/full/asp-and-sqlserver-tutorial 1/17

Boston University School of ManagementIS465 – 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). Basedon your earlier class, you should have these in place. Please test to make sure thatyour login account is still valid and that your directory is still accessible to you forread, 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 isgoing to act both as the server and as the client. The teaching server performs theroles of 2 servers in our specific situation: it hosts the web and hence acts as theweb 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 forproviding us with the constructs we need to access the SQL server database andmore importantly, to work with ASP.

- The Active Server Pages (ASP) is an extension of the web server (IIS) that allowsyou to do server-side scripting. At the same time, it also provides you with acompendium of objects and components that manage the interaction between theweb server and your browser. These objects can be manipulated by scriptinglanguages. We will be using VBScript as the scripting language for illustrating accessto 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 usedfunctions like converting text to HTML or URL. ActiveX Data Objects (ADO) usedto access and manipulate the SQL server database is a part of the Server object.

- Application Object – used to manage the different applications that are runningagainst 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 standardcreated by Microsoft in 1992 that allows you to add ODBC statements to programs

Page 2: ASP and SQLServer Tutorial

8/2/2019 ASP and SQLServer Tutorial

http://slidepdf.com/reader/full/asp-and-sqlserver-tutorial 2/17

so that the program may access and manipulate data in databases. ODBC driversare software modules that permit access to the different databases. The ODBCinterface (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 notstored in a conventional (relational or Access) database? The answer is the OLE-DB.

- OLE-DB – In 1997, Microsoft provided another easier specification for an interfacecalled OLE-DB and tried very hard to make sure that it is faster and easier to usethan ODBC. The OLE-DB allows a program to access information in any type of datastore (databases, or other files like email folders, spreadsheets, graphs etc.).Eventually, OLE-DB may replace ODBC completely. For now, it sits on top of theODBC drivers and allows you to use existing ODBC drivers. The OLE-DB equivalentof an ODBC driver is called a PROVIDER. A good definition of a PROVIDER issomething that provides data! PROVIDERS are NOT THE SAME as DRIVERS.There are many more drivers available than there are PROVIDERS. So if you needto 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 PROVIDERand so you do not have to know a great deal (in fact nothing) about the DRIVERused for accessing a database. Microsoft SQL Server is one such database wherethe PROVIDER will take care of everything and you don’t need the ODBC driver.OLE-DB PROVIDER is not available (yet) for ORACLE, SYBASE and otherdatabases 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-DBPROVIDER for accessing the SQL Server. This has some advantages that aredescribed 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 isestablished, the object may be re-used any number of times as you want in yourprogram code. The other two objects (Command and Recordset) are bothsublcasses of the Connection Object. Hence you do not always need aConnection object to connect to the database as each of the other two canconnect to the database as well.

Ø The Command Object is used to define and run the SQL commands against thedatabase. These commands are NOT IN ASP but in the language you know asSQL. The commands are typically used to return information from a database butcan 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 informationthat is retrieved from the databases (the records) and we need to be very carefulabout how these objects are created and used. The Recordset object can beused to view and alter the databases. It is used to find specific records, movethrough the database one record at a time, delete records, restrict access tosensitive information from specific users, sort records, and update one or more ofthe existing records.

Page 3: ASP and SQLServer Tutorial

8/2/2019 ASP and SQLServer Tutorial

http://slidepdf.com/reader/full/asp-and-sqlserver-tutorial 3/17

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 aspecific database. The systems administrator of the server is responsible forsetting up the DSN on that server. If DSN is used, then as mentioned in part 3above, the Command and Recordset Objects can directly be used to connect tothe server and you don’t really need the Connection object. What if you areunable 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 tothe database. The Command and Recordset objects will be used to do thespecific purpose each was designed to do and will not be used to connect to thedatabase. You will see a detailed example below that illustrates the use of all ofthese 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 aform window and retrieve and display the results in another page. The results will bedisplayed by formatting the data into a HTML table.

Ø Input Form (sqlcommand.html)

1. <HTML>2. <HEAD>

3. <TITLE> SQL Entry Form </TITLE>

4. </HEAD>

5. <BODY>

6. <h1 align="Center">ENTER SQL BELOW </h1>7. <FORM id="Sqlform" name="Sqlform" action="runsql.asp" method="post">

8. <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 inwhich uses may enter SQL codes (line 8), a submit button that executes theSQL 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 anasp code file “runsql.asp”, as indicated by the phrase action=”runsql.asp” andthat the method used to send the user input is “POST”, as indicated by thephrase 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:

Page 4: ASP and SQLServer Tutorial

8/2/2019 ASP and SQLServer Tutorial

http://slidepdf.com/reader/full/asp-and-sqlserver-tutorial 4/17

 

Ø The Executable ASP file (runsql.asp)

1. <%@ Language=VBScript %> 2. <HTML> 

3. <HEAD> 

4. <TITLE> SQL Results </TITLE> 

5. </HEAD> 

6. <BODY> 

7. <%8. 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 torun </h2></Center>")

12. Else

13. objConn.Open "PROVIDER=MSDASQL;DRIVER={SQLServer};SERVER=TEACHSERV;DATABASE=pubs;UID=xxxx;PWD=xxxx"

14. set objRS=objConn.Execute(cstr(Request.Form("Sqltext")),intRecordsAffected)

15. If intRecordsAffected = -1 Then16. 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> 

Page 5: ASP and SQLServer Tutorial

8/2/2019 ASP and SQLServer Tutorial

http://slidepdf.com/reader/full/asp-and-sqlserver-tutorial 5/17

31. <% If IsNull(objField) Then

32. Response.Write ("&nbsp;")

33. Else

34. Response.Write (objField.Value)

35. End If36. %> 

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 EntryForm </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 providedby the user (line 17), and presents the result to the user in a table (line 23 to47). The following line-by-line explanation will show in more details how thescripts manage to do so.

1. <%@ Language=VBScript %> 

We learned earlier that ASP uses server-side scripting. Here we see that server-sidescripts is inserted in an ASP file between<% and %> delimiters. It is this server-sidescript that enables us to generate HTML document dynamically. When an ASP file isexecuted on the server, the script gets executed and the results are reflected in theresulted HTML document. We will see this point more clearly later.

Line 1 tells the server that the language under use is VBScript. Note the ‘@’ characterright after the ‘<%’ delimiter.

2. <HTML> 

3. <HEAD> 4. <TITLE> SQL Results </TITLE> 

5. </HEAD> 

6. <BODY> 

These are standard HTML statements. It tells that this file is in <HTML> format and thetitle of the page is ‘SQL results’.

7. <%

8. Dim objRS, objConn

9. set objConn = Server.CreateObject("ADODB.Connection")

Page 6: ASP and SQLServer Tutorial

8/2/2019 ASP and SQLServer Tutorial

http://slidepdf.com/reader/full/asp-and-sqlserver-tutorial 6/17

 Line 7 indicates start of server-side scripts. Line 8 declares two variables, objRS andobjConn. 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. Inline 9, a connection object is created and assigned to objConn. Note that so far we haveconnected 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 torun </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 inputand outpout. In line 11, with the help of Form collection, we retrieve data contained inSqltext 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 QueryStringcollection instead (You may ask what a collection is. Well, just consider it as a set ofvalues 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 convertsthe parameter to a string. Therefore, line 11 examines if the user has inputtedsomething. 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 beinggenerated. 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 acommand 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 inthe semantics. For example, in VBScript, If … Then … Else … Else If is used to runvarious blocks of code depending on conditions. Don’t 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 aclosing “}”. Notice the matching “End If” is way behind in line 49. We will explain otherflow controls when they are used in the codes.

So this fragment judges if user has inputted a command, if not, an error message isdisplayed. If yes, we try to establish a connection with the database in use with line 14and 15:

13. objConn.Open "PROVIDER=MSDASQL;DRIVER={SQLServer};SERVER=TEACHSERV;DATABASE=pubs;UID=XXXX;PWD=XXXX"

Declared in line 8 and assigned in line 10, Connection object objConn was connected todatabase here in line 14. The general form of the Open method for the connection objectis:

Connection .Open ConnectionString

The ConnectionString parameter is a string that specifies a data source either as a datasource name (DSN), or by specifying a detailed connection string made up of individualparameter =value arguments separated by semicolons, and containing no spaces(DSN-less connections discussed earlier). You probably can tell that we are using DSN-less

Page 7: ASP and SQLServer Tutorial

8/2/2019 ASP and SQLServer Tutorial

http://slidepdf.com/reader/full/asp-and-sqlserver-tutorial 7/17

connection here. In our example, we are telling the server that database to be connectedis a pubs on the teaching server, whose name is “TEACHSERV ”. The provider for thedatabase 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 weneed 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 dataretrieved from the command in a Recordset object objRS. Later, we can access the databy referring to objRS. The second augment in calling Execute(), intRecordsAffected,holds the number of records that is changed after the command is executed. Notice thata negative value in intRecordsAffected suggests no record is changed but the Recordsetis 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 endsthis 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 theuser 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. <Center><h2>SQL RESULTS </h2> 

19. <b>SQL Statement:</b><%= cstr(Request.Form("Sqltext")) %> 

20. <p> 

Line 18-20 put the title of the table and the command used in the center of the browserwinder. There is a shot script <%= cstr(Request.Form("Sqltext")) %> embedded inline 19. This script means to put here the value of the “Sqltext”. When the server runsthis script, the value of “Sqltext” takes the place of this script in the resulted HTMLdocument. Don’t forget the ‘=’ before the cstr().

Line 21 to line 41 describes how to generate the table. We want the head of the table todisplay the names of the columns, and then each row in the Recordset objRS takes arow in the table.

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> 

Page 8: ASP and SQLServer Tutorial

8/2/2019 ASP and SQLServer Tutorial

http://slidepdf.com/reader/full/asp-and-sqlserver-tutorial 8/17

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 generatedHTML 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 startand end of a head.

The For Each … Next loop from line 23 – 25 repeated fill the name of each field into thetable head. You can interpret line 23 as “For each field in the Recordset objRS”. Notethat objRS.Fields is a collection of Field object, and objField is an variable name bywhich 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 actualfield 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 pointcan be seen more clearly when we compare the source code of the resulted HTMLdocument with the ASP source code.

Now that the table head is done, we can put the content in the Recordset into the table.

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 If36. %> 

37. </TD> 38. <% Next

39. objRS.MoveNext %> 40. </TR> 

41. <% Loop %> 

42. </TABLE> 

This Do While … Loop block, functioning like While-loop in C++, enable us to turn toeach record in a Recordset. When a non-empty Recordset is opened, the systemautomatically set the first record as the current record. You can navigate the Recordsetwith 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 TRUEwhen 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 arow in the table. Again that they are nested in the Do While … Loop block suggests eachtime the loop iterates, they will be put into the resulted HTML document. Similar to howthe 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.

Page 9: ASP and SQLServer Tutorial

8/2/2019 ASP and SQLServer Tutorial

http://slidepdf.com/reader/full/asp-and-sqlserver-tutorial 9/17

In this code fragment, the ASP scripts and HTML tags are heavily mixed. You shouldpay 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 memorydynamically allocated to the pointers when you are done with them in C++). Line 47 andline 48 displays the number of records affected in the browser window and line 50 addsa 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:

Page 10: ASP and SQLServer Tutorial

8/2/2019 ASP and SQLServer Tutorial

http://slidepdf.com/reader/full/asp-and-sqlserver-tutorial 10/17

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 namesand allows user to choose author by last name. The second ASP accepts user choiceand 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={SQLServer};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=Nothing23.%> 

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 theuser 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 ofan asp code file “AuthorQuery.asp”, as indicated by the phraseaction=”AuthorQuery.asp” and that the method used to send the user input is“GET”, not the POST method in example 1. Again “GET” method appendsthe 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 thedatabase directly through a Recordset object, RS . Recall that in Example 1,we first open a Connection object and then set the Recordset object with

Page 11: ASP and SQLServer Tutorial

8/2/2019 ASP and SQLServer Tutorial

http://slidepdf.com/reader/full/asp-and-sqlserver-tutorial 11/17

Execute method of the Connection object. Here we achieve the same goal bycalling the open method of Recordset object. The general form for Openmethod of Recordset is: 

Recordset.Open Source, ActiveConnection, CursorType, LockType, Options

In the example, the Open method takes first two parameters: the first one isthe SQL command that is used to retrieve the qualified data from thedatabase, and the second is the connection string. Notice that the string isexactly the same as the one we used in Example 1 to open the Connectionobject (Line 13).

The second ASP script fragment, Line 15 to 23, fills the list with the lastnames retrieved from the database. Pay attention to how Response.write putHTML tags and each individual last name to form the description on the list

options.

Ø Screen Snapshot

Ø Handling Page (authorQueryFrom.asp)

1. <%@ Language=VBScript %> 

2. <HEAD><TITLE>Author Query Result</TITLE></HEAD> 

3. <BODY> 

4. <%

5. 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

Page 12: ASP and SQLServer Tutorial

8/2/2019 ASP and SQLServer Tutorial

http://slidepdf.com/reader/full/asp-and-sqlserver-tutorial 12/17

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.MoveNext31. 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 auser defined subroutine, called MakeTable(line 6 to line 36). The commandstring was retrieved in line 37, with the help from QueryString collection fromRequest object. Line 39 construct the SQL command to be used. Notice howa string constant is formed (with character ‘ on both side of lname).

Ø Subroutine MakeTable takes the SQL command and the connection string asthe 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 commandin red color. Table is defined in line 15 to line 33. Line 16 to 18 defines thehead and the rows are filled in with a nested loop: Do WHILE … LOOP (Line19 to 32) loop for each record (row) and For ... Next loop for each field (line21 to 29).

Ø Screen snapshot: note the hightlighted part in the address bar. That’s wheredata are sent with “GET” method. 

Page 13: ASP and SQLServer Tutorial

8/2/2019 ASP and SQLServer Tutorial

http://slidepdf.com/reader/full/asp-and-sqlserver-tutorial 13/17

 

7. Example 3

This example shows an online survey on students’ background and their knowledgeabout programming and DBMS. Once student submits the survey, the answer is send tothe server and stored in a table, which already has the student’s ID. If the student’s IDcan’t 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 moreideas 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 tomyself and will only use it in aggregation. The student ID

information you input will only be used for making sure that each ofyou 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;

Page 14: ASP and SQLServer Tutorial

8/2/2019 ASP and SQLServer Tutorial

http://slidepdf.com/reader/full/asp-and-sqlserver-tutorial 14/17

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 master38.</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">No60.<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> 

Page 15: ASP and SQLServer Tutorial

8/2/2019 ASP and SQLServer Tutorial

http://slidepdf.com/reader/full/asp-and-sqlserver-tutorial 15/17

Ø Explanation: The logic in the source code is the same as that in the inputform for example 1. Note that you can improve the form by adding scripts tocheck 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 theserver.

Ø 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=windows-

1252"> 

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 = "" Then15. 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={SQLServer};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 inclass!"

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 inclass!"

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

Page 16: ASP and SQLServer Tutorial

8/2/2019 ASP and SQLServer Tutorial

http://slidepdf.com/reader/full/asp-and-sqlserver-tutorial 16/17

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 clientbrowser. One good thing of doing so is that you can end the response when youfind something is wrong, for example, when you find out the SID is empty (Line14), you can write an error message (line 15) and then end the response buycalling the End method of Response object (line 16).

18. Dim objRS19. 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 weused in example 1 and 2. Line 21 assigns a SQL command string. Don’t forgetthe ‘s around the sID. Line 22 opens the recordset. Recall that the general formof Open method is:

Recordset.Open Source, ActiveConnection, CursorType, LockType, Options

We have explained Source and ActiveConnection before. CursorType is theparameter that decides whether you can make change to the recordset and howyou can navigate in the recordset. Here we pass a 2, which stands for dynamiccursor. Dynamic cursor supports forward and backward navigation and allowsyou to make change to the records. When multiple users are updating the samedatabase, somebody else may happen to overwrite the modification you justmade to the database. (You will learn more on this down the road.) Locking isone mechanism that prevents such accident from happening. Here we use type 2lock: pessimistic lock which locks the entire record when we first start editing arecord.

23. If objRS.BOF Then24. Response.Write "Thanks for filling the survey and see you in

class!"

25. objRS.AddNew26. 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 itis empty, the server will set the BOF to true upon opening it. Therefore, if it isempty, the SID cannot be found in the database and we have to create a new

Page 17: ASP and SQLServer Tutorial

8/2/2019 ASP and SQLServer Tutorial

http://slidepdf.com/reader/full/asp-and-sqlserver-tutorial 17/17

entry for it using AddNew (Line 25). Otherwise, the server will set the first recordas current record.

Line 31 to 38 updates the current record. Note how we access to a particular fieldwith the field name: by putting the field name in the ()s. To make the new valuesactually get in the database, line 39 calls the Update command to commit thechange.

8. Several tips

Ø Remember you are writing VBScripts and not C++ program: there is no ; aftereach sentences; in most cases, you cannot bring a line of code into severallines; the “equal to” operator is a single ‘=’ not ‘==’; the “not equal to” operator is‘<>’ not ‘!=’; and finally, there are commands that don’t 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 asthat 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 ifthe constructed SQL command is correct or not, you can always put it into theresponse and check it in the browser:

sql = "SELECT * FROM IS467A1 WHERE SID='" + sID + "'"Response.Write sql 


Recommended