22
ASP Application ASP Application Development Development Session 3 Session 3

ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

  • View
    237

  • Download
    2

Embed Size (px)

Citation preview

Page 1: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

ASP Application DevelopmentASP Application Development

Session 3Session 3

Page 2: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

Topics CoveredTopics Covered

Using SQL Statements for:Using SQL Statements for:– Inserting a tupleInserting a tuple– Deleting a tupleDeleting a tuple– Updating a tuple Updating a tuple

Using the RecordSet Object for:Using the RecordSet Object for:– Inserting a tupleInserting a tuple– Deleting a tupleDeleting a tuple– Updating a tupleUpdating a tuple

Page 3: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

ASP Session ObjectASP Session Object

The Session object is used to store information The Session object is used to store information about, or change settings for a user session.about, or change settings for a user session.

Variables stored in the Session object hold Variables stored in the Session object hold information about one single user, and are information about one single user, and are available to all pages in one applicationavailable to all pages in one application

<% Session("username")=“JoeShmoe" Session("age")=23%>

Welcome <%Response.Write(Session("username"))%>

<% Session.Timeout=5 %>

The example below sets a timeout interval of 5 minutes:

Page 4: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

ASP Application ObjectASP Application Object

A group of ASP files that work together to perform A group of ASP files that work together to perform some purpose is called an application.some purpose is called an application.The Application object in ASP is used to store The Application object in ASP is used to store variables and access variables from any page, variables and access variables from any page, just like the Session object. just like the Session object. The difference is that all users share ONE The difference is that all users share ONE Application object, while with Sessions there is Application object, while with Sessions there is one Session object for each user.one Session object for each user.

<%

Sub Application_OnStart

application("vartime")=""

application("users")=1

End Sub

%>

There are<% Response.Write(Application("users")) %> active connections.

In the example we have created two Application variables: "vartime" and "users".

You can access the value of an Application variable like this.

Page 5: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

Controlling Application BehaviorControlling Application Behavior

You can create Application variables in You can create Application variables in "Global.asa" "Global.asa" ASP The Global.asa file:ASP The Global.asa file:– The Global.asa file is an optional file that can The Global.asa file is an optional file that can

contain declarations of objects, variables, and contain declarations of objects, variables, and methods that can be accessed by every page methods that can be accessed by every page in an ASP applicationin an ASP application

ASP Including Files :ASP Including Files :– The #include directive is used to create The #include directive is used to create

functions, headers, footers, or elements that functions, headers, footers, or elements that will be reused on multiple pageswill be reused on multiple pages

<html><body><!--#include file=“header.asp"--></p>Hello…… <p><!--#include file=“footer.asp"--></p></body> </html>

Page 6: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

RecordSet ObjectRecordSet Object

Recordset objects can support two types of Recordset objects can support two types of updating: updating: 

– Immediate updatingImmediate updating

all changes are written immediately to the all changes are written immediately to the database once you call the Update method database once you call the Update method

– Batch updatingBatch updating

the provider will cache multiple changes the provider will cache multiple changes and then send them to the database with and then send them to the database with the UpdateBatch methodthe UpdateBatch method

Page 7: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

Cursor TypesCursor Types

In ADO there are 4 different cursor types defined:In ADO there are 4 different cursor types defined:– Forward-only cursorForward-only cursor

Allows you to only scroll forward through the Recordset. Additions, Allows you to only scroll forward through the Recordset. Additions, changes, or deletions by other users will not be visible. changes, or deletions by other users will not be visible. 

– Keyset cursorKeyset cursorLike a dynamic cursor, except that you cannot see additions by other Like a dynamic cursor, except that you cannot see additions by other users, and it prevents access to records that other users have deleted. Data users, and it prevents access to records that other users have deleted. Data changes by other users will still be visible. changes by other users will still be visible.

– Dynamic cursorDynamic cursorAllows you to see additions, changes, and deletions by other users. Allows you to see additions, changes, and deletions by other users.

– Static cursorStatic cursorProvides a static copy of a recordset for you to use to find data or generate Provides a static copy of a recordset for you to use to find data or generate reports. Additions, changes, or deletions by other users will not be visible. reports. Additions, changes, or deletions by other users will not be visible. This is the only type of cursor allowed when you open a client-side This is the only type of cursor allowed when you open a client-side Recordset object. Recordset object.

Page 8: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

Cursor TypesCursor Types

Page 9: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

Lock TypesLock Types

Page 10: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

Inserting a Tuple using SQL StatementInserting a Tuple using SQL Statement

User inputs new data in a formUser inputs new data in a formGather that data and create an SQL Gather that data and create an SQL statementstatementOpen connection to the databaseOpen connection to the databaseExecute the SQL statementExecute the SQL statementSyntax for SQL statement:Syntax for SQL statement:– insert into tablename (attribute list) Values insert into tablename (attribute list) Values

(actual values)(actual values)– ExampleExample

insert into tblStudent (StudentNo, FirstName, LastName, insert into tblStudent (StudentNo, FirstName, LastName, Year, Major) values (45, ‘Joe’, ‘Shmoe’, 2000, MIS)Year, Major) values (45, ‘Joe’, ‘Shmoe’, 2000, MIS)

insert into tblStudent values (45, ‘Joe’, ‘Shmoe’, 2000, MIS)insert into tblStudent values (45, ‘Joe’, ‘Shmoe’, 2000, MIS)

Page 11: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

Inserting a Tuple – Form to input dataInserting a Tuple – Form to input data<html> <!-- Filename: enter_student_data.htm --><body><form method=post action=insert_student.asp><br><br><center><font size=5 face=arial color=#336699><b>Student Information Form</b><br><br></font><font size=4 face=arial color=black>Please enter the following student information and click on the Add button.<br><br><br><table><tr><td>Student Number</td> <td> <input type=text name=sno size=20></td></tr><tr><td>First Name </td> <td> <input type=text name=fname size=20></td></tr><tr><td>Last Name </td> <td> <input type=text name=lname size=20></td></tr><tr><td>Year</td> <td> <input type=text name=year size=20></td></tr><tr><td>Major </td> <td> <input type=text name=major size=20></td></tr></table><br><input type=submit value="Add Student Information"></center></font></form></body>

Call the ASP page

Text Boxes for attributes

Submit button to send the values

Demo the Example

Page 12: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

Inserting a Tuple – ASP PageInserting a Tuple – ASP Page<html> <head> <!-- Filename: insert_student.asp --><meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <title>Get Product from Form</title> </head> <% 'get the user entered datasn=request.form("sno")fn=request.form("fname")ln=request.form("lname")yr=request.form("year")mj=request.form("major")

'Establish the connection with the admin databaseset my_conn= Server.CreateObject("ADODB.Connection")

'Construct the connection string using relative path for the database filemyvar = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=" & _ server.mappath("db/admin.mdb")

'Open the connection to the data sourcemy_conn.Open myvar

'create sql query using the user entered dataStrSql= "insert into tblStudent (StudentNo, FirstName, LastName, Year, Major) values (" & _ sn & ",'" & fn & "','" & ln & "'," & yr & ",'" & mj & "');"

'continued on the next slide

Get the user input and store in variables

DSN-less connection string

Construct the DML statement using thevariables that contain the user values

String values are delimeted using single quotesNeed to add comma to separate each value

Page 13: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

Inserting a Tuple – ASP Page (continued)Inserting a Tuple – ASP Page (continued)

'print out the SQL query to see if it is constructed properlyresponse.write "<h3>SQL Statement Created: </h3> &nbsp&nbsp&nbsp" & StrSql

'execute the query which will insert the tuple into the table tblStudentmy_conn.Execute (StrSql)

'display message saying the typle is inserted response.write "<br><br>Inserted the tuple for <b>" & fn & " " & ln & "</b>"

my_conn.Close%>

<br><br>Click on this <a href=select_student.asp><b>link</b></a> to see if the student has been added.<body> </body></html>

For debugging purposes, it is a good ideato print out the sql statement that is constructed

Execute the SQL statement

Just a confirmation message

Call another ASP page that lists all the student namesin the table to make sure the tuple was actually inserted.Don’t have to do this in your application

Page 14: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

Deleting a TupleDeleting a Tuple

User identifies the tuple to deleteUser identifies the tuple to deleteConstruct the delete SQL statementConstruct the delete SQL statementExecute the SQL statementExecute the SQL statementSyntax of delete statementSyntax of delete statement– DELETE From Tablename WHERE DELETE From Tablename WHERE primarykey = valueprimarykey = value

– ExampleExample"DELETE FROM tblStudent WHERE "DELETE FROM tblStudent WHERE StudentNo = 87" StudentNo = 87"

Page 15: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

Deleting a Tuple Example – Get User InputDeleting a Tuple Example – Get User Input<!-- Filename: delete_start.asp Calls: delete_SQL.asp --><html> <head> <title>Get Product from Form</title> </head> <% 'Establish the connection with the nowrthwind databaseset my_conn= Server.CreateObject("ADODB.Connection")'Construct the connection string using relative path for the database filemyvar = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=" & server.mappath("db/admin.mdb")'Open the connection to the data sourcemy_conn.Open myvar'Get the student information from the tblStudent tableStrSql= "Select * from tblStudent" set rs = my_conn.Execute (StrSql) %> <body> <h1>Deleting a Student from tblStudent Table</h1><h3>Please select a student and click on the Delete Student button <br> to remove the student.</h3><form method="post" action="delete_SQL.asp">Select a student Name: &nbsp<select name="student"><% do while not rs.eof %> <option value="<%=rs("StudentNo")%>"><%=rs("FirstName")%>&nbsp<%=rs("LastName")%></option> <% rs.movenext loopmy_Conn.Closeset my_conn = nothing%></select> <br><br><input type="submit" value="Delete Student"></form> </body> </html>

Create the drop-down list called “student”

For each option, the value is set as the StudentNo, whichwill be sent to the next ASP page

Demo the Example

Page 16: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

Deleting a Tuple Example – ASP pageDeleting a Tuple Example – ASP page<html> <head> <!-- Filename: delete_SQL.asp --><title>Delete a Tuple</title> </head>

<% 'get the student number that was selectedselected_id = request.form("student")

'Establish the connection with the admin databaseset my_conn= Server.CreateObject("ADODB.Connection")

'Construct the connection string using relative path for the database filemyvar = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=" & _ server.mappath("db/admin.mdb")

'Open the connection to the data sourcemy_conn.Open myvar

'create the sql query using the user entered data for student number StrSql= "DELETE FROM tblStudent WHERE StudentNo = " & selected_id

'print out the SQL query to see if it is constructed properlyresponse.write "<h3>SQL Statement Created: </h3> &nbsp&nbsp&nbsp" & StrSql

'execute the query which will insert the tuplemy_conn.Execute (StrSql)

my_conn.Close %>

<br><br>Click on this <a href=select_student.asp><b>link</b></a> to see if the student has been deleted.<body> </body></html>

Page 17: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

Updating a TupleUpdating a Tuple

User identifies the tuple to updateUser identifies the tuple to updateGet the new values for attributesGet the new values for attributesCreate the appropriate SQL statement with Create the appropriate SQL statement with new values new values Execute the SQL statementExecute the SQL statementSyntax of update statementSyntax of update statement UPDATE Tablename SET UPDATE Tablename SET AttributeName = new valueAttributeName = new value AttributeName = new valueAttributeName = new value WHERE primarykey = valueWHERE primarykey = value– ExampleExample

UPDATE tblStudent SET LastName = “Shmoe”UPDATE tblStudent SET LastName = “Shmoe” WHERE StudentNo = 87"WHERE StudentNo = 87"

Page 18: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

Updating a Tuple - ExampleUpdating a Tuple - Example<html> <body> <!-- Filename: update_start.asp --><% set conn=Server.CreateObject("ADODB.Connection")myvar = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=" & _ server.mappath("db/admin.mdb")conn.Open myvarstrsql = "SELECT * FROM tblStudent"set rs = conn.execute(strsql) %><h2>Student Information </h2><table border="1" width="60%"> <tr><%for each x in rs.Fields response.write("<th>" & ucase(x.name) & "</th>")next%> </tr><% do until rs.EOF %> <tr> <% for each y in rs.Fields if y.name="StudentNo" then%> <td> <form method="post" action="update_student.asp"> <center /> <input type="submit" style="width:75px" name="StudentNo" value="<%=y.value%>"></td></form> <%else%> <td><%Response.Write(y.value)%></td> <%end if Next rs.MoveNext%></tr><%loopconn.close%></table></body></html>

Conection string

Get all the tuples from the tblStudent tableand create the recordset object “rs”

Create a table and output the attribute namesas the first row of the table

Subsequent rows contain values for each student. First field in each row of the table corresponds to StudentNo and contains a form with a submit button. When clicked, calls the next ASP page

Output the values of other attributes in each row of the table.

End of the do … until loop

Demo the Example

Page 19: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

Updating a Tuple Continued (ASP Page)Updating a Tuple Continued (ASP Page)

<html><body><h2>Update Student Record</h2><% set conn=Server.CreateObject("ADODB.Connection")myvar = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=" & _ server.mappath("db/admin.mdb")conn.Open myvarsid=Request.Form("StudentNo")strsql = "SELECT * FROM tblStudent WHERE StudentNo=" & sidif Request.form("FirstName")="" then set rs = conn.execute(strsql) %> <form method="post" action="update_student.asp"> <table> <%for each x in rs.Fields%> <tr> <td><%=x.name%></td> <td><input name="<%=x.name%>" value="<%=x.value%>"></td> <%next%> </tr></table><br><br> <input type="submit" value="Update record"> </form><%else sql="UPDATE tblStudent SET " sql=sql & "FirstName='" & Request.Form("FirstName") & "'," sql=sql & "LastName='" & Request.Form("LastName") & "'," sql=sql & "Year=" & Request.Form("Year") & "," sql=sql & "Major='" & Request.Form("Major") & "'" sql=sql & " WHERE StudentNo=" & sid on error resume next conn.Execute sqlend ifconn.close %> </body></html>

The first time this page is called, it willhave value for only “StudentNo”

If first time, execute sql andretrieve information for theselected sid. Create a form withtext fields to edit

Output the field name followed bya text box with the value. User canedit the values and click on submit.The same ASP page is called again

The second time around, the text fieldswill have the new values. Construct anUpdate statement using those valuesand execute that query.

<!-- Filename: update_student.asp -->

Page 20: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

Adding A Record Through RecordSet Adding A Record Through RecordSet <html> <head> <title>Add a Record</title> </head> <body><% 'Establish the connection with the admin databaseset my_conn= Server.CreateObject("ADODB.Connection")'Construct the connection string myvar = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=" & _ server.mappath("db/admin.mdb")'Open the connection to the data sourcemy_conn.Open myvar Dim oRS Set oRS=Server.CreateObject("ADODB.Recordset") oRS.CursorType = 2 oRS.LockType = 3 strsql = "select * from tblStudent" oRS.Open strsql, my_conn oRS.AddNew oRS.Fields("StudentNo")=Request.Form("sno") oRS.Fields("FirstName")=Request.Form("fname") oRS.Fields("LastName")=Request.Form("lname") oRS.Fields("Year")=Request.Form("year") oRS.Fields("Major")=Request.Form("major") oRS.Update'display message saying the typle is inserted response.write "<br><br>Added the record for <b>" & Request.Form("fname") & _ " " & Request.Form("lname") & "</b>" oRS.Close my_conn.Close%> <br><br>Click on this <a href=select_student.asp><b>link</b></a> to see if the student has been added.</body></html>

Create an instance of RecordSet objectcalled oRS and set the appropriateCursorType and LockType

Execute SQL statement and get thecurrent records from the table

Add a new record to the recordset object

Provide values for each of the attributes

Update the recordset object which thenupdates the base table

<!-- Filename: add_record.asp -->

Demo the Example

Page 21: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

Deleting a Record using RecordSet ObjectDeleting a Record using RecordSet Object<html> <head> <!-- Filename: delete_record.asp --><title>Delete a Tuple</title> </head>

<% 'get the student number that was selectedselected_id = request.form("student")

'Establish the connection with the admin databaseset my_conn= Server.CreateObject("ADODB.Connection")

'Construct the connection string myvar = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=" & _ server.mappath("db/admin.mdb")'Open the connection to the data sourcemy_conn.Open myvar

Dim oRS Set oRS=Server.CreateObject("ADODB.Recordset") oRS.CursorType = 2 oRS.LockType = 3 strsql = "select * from tblStudent" oRS.Open strsql, my_conn

oRS.Find "StudentNo=" & selected_IDoRS.delete my_conn.Close %>

<br><br>Click on this <a href=select_student.asp><b>link</b></a> to see if the student has been deleted.<body> </body></html>

Demo the Example

Create the RecordSet object oRS and set The appropriate cursor type and lock type

Get the selected StudentNo andstore it in a variable

Open the oRS recordset object by executingthe SQL statement (strsql) through the connection object (my_conn)

Find the record with the selected StudentNoThe current record pointer points to that recordDelete that record by calling the delete method

Page 22: ASP Application Development Session 3. Topics Covered Using SQL Statements for: –Inserting a tuple –Deleting a tuple –Updating a tuple Using the RecordSet

ASP Exercise 3ASP Exercise 3Create an ASP application to manage a tableCreate an ASP application to manage a table

Use the Employee table in Use the Employee table in exercise3.mdbexercise3.mdb

Initial page with choices for viewing the data, adding, Initial page with choices for viewing the data, adding, deleting, or updating a recorddeleting, or updating a record

View optionView option– Call an ASP page to display the records in the employee tableCall an ASP page to display the records in the employee table

Add optionAdd option– Call an ASP page for entering employee dataCall an ASP page for entering employee data– Call another ASP page for adding the record to the Call another ASP page for adding the record to the

employee tableemployee table

Delete optionDelete option– Call an ASP page to indicate the record to be deletedCall an ASP page to indicate the record to be deleted– Call an ASP page to delete the recordCall an ASP page to delete the record

Update optionUpdate option– Call an ASP page to indicate the record to be updatedCall an ASP page to indicate the record to be updated– Call an ASP page to update the recordCall an ASP page to update the record