1
Database Programming Summary
John Lamertina
Reference: Riccardi, G, Database Management with Web Site Development Applications, Addison-Wesley, 2003
2
Content⢠Part I: Introduction
â Chapters 1 and 2
⢠Part II: Design Information Systemsâ Chapters 3 and 4
⢠Part III: Design Relational Databasesâ Chapters 5, 6, and 7
⢠Part IV: Manipulate Relational Informationâ Chapters 8 and 9
⢠Part V: Create Interactive Web Sitesâ Chapters 10, 11, and 12
3
Chapter 1Introduction to Information and
Database Systems
I. Introduction
4
How Do Databases Represent Information?
⢠The physical database:â a collection of files containing the data content
⢠The schema: â a specification of the physical databaseâs information content
and logical structure
⢠The database engine: â software that lets people access and modify the database
contents
⢠The data definition and manipulation languages: â programming languages, such as Java or SQL (Structured
Query Language), that let software developers define the schema and access the database
5
How Do Databases Represent Information?
⢠Relational database management system (RDBMS)â Tables of dataâ Schema
⢠Name of table⢠Names and types of attributes
â Contents⢠Row is a fact⢠Attribute value is a characteristic
6
Example of storing customer information
Customer table accountId lastName firstName
101 Block Jane
102 Hamilton Cherry
103 Harrison Kate
104 Breaux Carroll
Logical description (Schema)
Customer (accountId, lastName, firstName)
Table creation statement
create table Customer (accountId integer, lastName char(20), firstName char(20))
7
Chapter 2Internet Information Systems
8
Components of the Web⢠Web browser
â Formats and displays Web pagesâ Requests pages from Web serverâ Collects user inputs and sends
them to server⢠Web server
â Sends Web pages to browserâ Accepts and processes user inputâ Sends requests to information
server⢠Information Server
â Accepts requests from Web serverâ Manages complex information
resourcesâ Contains database server
9
Web Server⢠A computer program that services browser requests
â A Web server is software that knows how to service requestsâ A Web server computer is a computer that executes a Web server program
⢠Browser request for a specific HTML document may be serviced from the Web server computerâs disk
http://www.web4data.com/index.html
www.web4data.com
<html><head>... </html>
Files
<html><head>... </html> /index.html
WebServer
WebBrowser
10
Generating HTML Documents⢠An Information Server may be a computer that generates HTML
documents for storage in a Web serverâ New York Times has regular updates of its pages from an information
server that contains all of its news stories and other informationâ Someone requests the recreation of the home page (index.html)
www.nytimes.com
Files
index.html:<html><head>...</html>
index.html:<html><head>...</html>
generateindex.html
WebServer
InformationServer
11
Sample SQL Statement⢠SQL (Standard Query Language) is the language that is used to
communicate with database servers⢠The information for the sales receipt entries is produced by
sending this SQL statement to the BigHit Online database serverâ select Movie.movieId, Movie.title, Sale.format, Movie.dvdPrice,
Movie.tapePrice, Sale.quantity, Sale.cost from Movie, Sale where Movie.movieId = Sale.movieId and Sale.accountId =
101 and Sale.saleDate = 'Mar 5, 2002'
12
Chapter 3Representing Information with
Data Models
II. Design Information Systems
13
What is a Data Model?⢠A data model is a precise description of information
content⢠Types of data models
â Conceptual: in terms that users will understandâ Logical: in terms that a relational database system will understandâ Physical: in terms of the underlying computer hardware and
operating system
⢠Database schemasâ Schema is another word for model that implies that it adheres to a
particular strategy for defining modelsc
14
Organizing Information⢠To understand data modeling we must learn many new technical terms⢠Entity
â A thing (object) that is of interest to an information systemâ An abstraction of the object that contains those characteristics that are important to
the information system⢠Entity class
â The common characteristics that represent a set of entitiesâ The common characteristics of a particular set of entities that make them distinct from
other entities⢠Attribute value
â A characteristic of an entityâ The value of a particular characteristic
⢠Attributeâ A characteristic that helps to describe an object
⢠Examplesâ Entity: A customer, or the characteristics of a customer that are of interestâ Entity class: All of the potential customers, or the information about themâ Attribute: hair color or last nameâ Attribute value: hair color is brown or last name is âBreauxâ
15
Discovering Relationships⢠A relationship is a connection between 2 entities
â Customer Jane Block rents the video with videoId 90987⢠A relationship type between 2 entity classes represents the possibility that
two entities may be relatedâ A customer may rent a video
⢠Attributes and relationship types are not the sameâ The customer accountId is not an attribute of the Video entity class
⢠What are the relationships, entities and attribute values in this video rental receipt?
⢠What entity classes, attributes and relationship types are implied by the video rental receipt?
BigHit Video Rental ReceiptAccount ID: 101 video ID:
90987Date: January 9,
2002Cost: $2.99
Jane Block1010 Main St.Apopka, FL 30458
Elizabeth Date due: January 11, 2002
Customer
RentalVideo
16
Case in Point⢠Determining entity classes, attributes and
relationship types for BigHit Online video sales⢠Process
â Evaluate statement of goals for information systemâ Define entity classesâ Define attributes for entity classesâ Define relationship typesâ Determine cardinalities of relationship rolesâ Add attributes to relationship types as necessaryâ Evaluate entity classes, attributes, and relationship types for
clarity, accuracy, and completeness
17
Chapter 4Data Modeling with
Entity-Relationship Diagrams
18
Terminology
Recall from Chapter 3:Entity Class: blueprint for individual objects (instances /
entities); the common characteristics for a collection of entities
Attributes: properties (characteristics) that describe an entity
Relationship Type: representation of the possible association between two or more entity classes (e.g. customer may rent a video; an employee may manage a store)
Cardinality Constraint: limitation on numbers (e.g. one, many, or other specific min or max)
M
19
Entity-Relationship Modeling⢠An E-R model is a data model that includes
â Entity classesâ Attributes of each classâ Relationship types between classesâ Constraints
⢠Types of attributes⢠Designation of key attributes⢠Cardinalities of relationship types
⢠An E-R Model is typically represented graphicallyâ E-R diagram, the technique we useâ UML diagram, an emerging standard for specifying E-R models
and software design
20
Entity Relationship Diagrams⢠Sample diagram for entity class Customer
lastName accountIdfirstName
numberRentals
balance
otherUsers
AttributeKey
Attribute
DerivedAttribute
Multi-valued
Attribute
Customer
address
zipcode
statecity
street
CompositeAttribute
ComponentAttribute
EntityClass
21
Relationship Types⢠Example of representing relationship type Owns between
classes Store and Video
RelationshipType
EntityClass
RelationshipAttribute
Store VideoOwns
costpurchaseDate
EntityClass
IsOwnedBy
AlternateRelationship
Name
22
Constraints on Relationship Types
⢠Example of cardinality and participation constraints
to-manyrelationship
role
Store VideoOwns
costpurchaseDate
To-onerelationship
role
OptionalparticipationConstraint
MandatoryparticipationConstraint
1 M
IsOwnedBy
Cardinality constraints
Participation constraints
1 Store owns Many Videos
A Video is owned by no more than 1 Store
1 Store may own Many Videos
A particular Video must be owned by exactly 1 Store
23
Modeling Video Rentals⢠Examples of current rentals and previous rentals⢠Differences are in cardinalities and attribute names
MCustomerM
VideoPreviouslyRented
dateRented
costdateReturned
1CustomerM
VideoRents
dateRented
costdateDue
1 Customer may rent Many Videos; a particular Video may be rented by
exactly 1 Customer (at a time)
A Customer may have previously rented Many Videos;
A Video may have previously been rented by Many Customers
A customer rents a video.
Customers previously rented videos.
24
Relationships Entities
E-R Symbols:⢠Entity Class: nouns (instances / entities)
⢠Attributes: adjectives (properties / characteristics) describe an entity
⢠Relationship: verbs (e.g. customer may rent a video; an employee may manage a store)
Relationship sometimes better represented as an equivalent Entity.
Rents Rental
25
Modeling Video Rentals as an Entity Class
⢠Diagram shows entity class Rental and its relationship types with Customer and Video
⢠Note cardinalities and participation constraintsâ A Rental entity cannot exist without being related to both a
customer and a video⢠Problem occurs because Rental has no key attribute
(no inherent primary key)
Video1
Customer1
Has Rental1
MHas
costdateDue dateRented
Note that we can now identify and collect attributes of a rental.
26
Weak Entity Classes⢠A weak entity class is
â An entity class with no key of its ownâ An entity class whose entities cannot exist without relation to other entities
⢠An identifying relationship type isâ A relationship type that determines the keys of the weak entitiesâ The weak entity class always has a to-1 relationship with owner entity
class.
Video1
Customer1
Has Rental1
MHas
IdentifyingRelationship
Type
Weak EntityClass
costdateDue dateRented
Owner EntityClass
27
Rental History
CustomerPreviously
Rented Video
dateRented
dateReturned cost
M M
We shall see that a Many to Many relationship is modeled by applying a pair of 1-to-Many relationships.
28
Rental History Options (a)
Customer PreviousRental Video Has HasM M1 1
videoID
dateRented
Convert Relationship to an Entity
Option2: composite primary key: videoID and dateRented â but this does not allow a video to be rented twice on the same dayOption3: use dateTimeRented instead of just dateRented
Customer PreviousRental Video Has HasM M1 1
videoID
Option1: composite primary key: videoID and customerID â but this does not allow customer to rent same movie twice
customerIDIdentifying Relationship
associates Weak Entity to Owner Entity with to-1 Cardinality
Thus, a Previous Rental is associated
with exactly one Video.
29
Rental History Options (b)
Customer PreviousRental Video Has HasM M1 1
videoIDdateRented
Option4: allow inactive Customers to be deleted by changing participation constraint to optional
30
Auction Web SiteProblem #10, page 87
Seller Item Offers
Placed on
M
M
1
1
ItemID
BidderID
Customer is SuperClass of Seller & Bidder
Bidder MakesM1
Bid
Bid is a weak entity class â it does not exist without an item.Thus, item has to-1 cardinality in relation to bid.
Wins
1
1
Highest Bid
PriceOpen
TimeEnd
ItemID
Amount
TimeBidderID
SellerIDA Seller may offer
many Items.
A Bidder may make many Bids.
Many Bids may be placed on an Item.
The Highest Bid may win Item (if that bid is at least
of a minimum value)
MinWinBid
An Item can be bid upon by many bids.
An Item can be won by a single highest bidder.
31
Chapter 5Defining Relational Data Models
III. Design Relational Databases
32
Basics of the Relational Model⢠The relational model represents information in tables (called relations)
â Each table represents a set of entitiesâ Each column of a table represents the attribute values of the entitiesâ Each row of a table represents a single entity
⢠A database schema is a collection of table definitions (relation schemas)⢠A relational database is a collection of tables
â Each table stores objects for a single relation schema
33
Relation Schemas and Keys⢠The rows of a relational table are unique
â No 2 rows have the same values for all of the attributes⢠A key is a collection of attributes in which
â No 2 rows have the same values for all attributes in the key⢠Every table must have a key
â Why?⢠A relation schema is the specification of the structure of a table
â Name of the tableâ Name and type of each attributeâ Declaration of the key
⢠A key declaration is a constraintâ A table is not allowed to have 2 different rows that have the same value for the
keyâ Database systems enforce key constraints
⢠By blocking any attempt to modify a table that will result in a violation of the key constraint
34
Relation is not Relationship⢠Be careful of these two words
â Relationâ Relationship
⢠A relation is a table that contains a set of entities⢠A relationship is a connection between two entities⢠We must be very careful to use the correct word
35
Representing Entity Classes⢠For each strong entity class in your E-R model create a relation schema:⢠Rule 1a: Define a relation schema by the same name.⢠Rule 1b: For each single-valued attribute of the entity class
â create an attribute by the same name in the relation schema and specify a type for the attribute
⢠Rule 1c: Define the key of the new relation schema as the key of the entity class
â If the entity class key consists of multiple simple attributes, the key of the relation schema will be that set of attributes.
â Underline your selected key attribute in each schema in order to identify the key.
36
Composite Attributes⢠Rule 2. For each composite attribute of a strong entity class
â create an attribute in the relation schema for each component attributeâ If appropriate, use the name of the composite attribute as a prefix for
each of the component attribute names ⢠Schema: Customer (accountId string, lastName string,
firstName string, street string, city string, state string, zipcode string, balance number)
accountId lastName firstName street city state zipcode balance101 Block Jane 1010 Main
St.Apopka FL 30458 0.00
102 Hamilton
Cherry 3230 Dade St.
Dade City
FL 30555 4.47
103 Harrison
Kate 103 Dodd Hall
Apopka FL 30457 30.57
104 Breaux Carroll 76 Main St.
Apopka FL 30458 34.58
37
One-to-Many RelationshipTypes⢠For a one-to-many relationship
typeâ Add the key attributes of one entity
class to the other entity class (foreign key attributes).
â Add the foreign key attributes to the class whose cardinality is 1
⢠Rule 3: For each one-to-many relationship type R between subject class S and target class T
â add the key attributes of class S to class T as foreign keys
â Name the attributes using the role that S plays in relationship type R
â Add the attributes of the relationship type R to target class T.
38
One-to-One Relationship Types
⢠The foreign key attributes may be added to either schemaâ Each entity class is to-one in the relationship type
⢠Choose which class to include the foreign key attributesâ One option is to try to minimize the number of null values
⢠Rule 4: For each one-to-one relationship type between two classes, choose one class to be the subject and one to be the targetâ Add the key attributes of the subject class to the target schema as
foreign key attributesâ Add the attributes of the relationship type to the target schema, just
as in Rule 3
39
Many-to-Many Relationship Types
StoreEmployeeMM
workerWorksIn
ssn storeId358-44-7865 3579-98-8778 5358-44-7865 5
⢠Many-to-Many relationship types between 2 classes cannot be represented as simple attributes in either related table
⢠Rule 5: For each many-to-many relationship type R between classes S and Tâ Create a new relation schema Râ Add attributes to represent the key of S and the key of T as foreign key
attributesâ The key of schema R is the combination of those attributesâ Add the relationship attributes to schema R, as in Rule 3
⢠Schema: WorksIn (ssn string references Employee, storeId number references Store)
40
Chapter 6Defining Relational Databases with
Microsoft Access
41
Chapter 7Improving Relational Schemas and
Normalization
42
Redundancy and Anomalies in Relation Schemas
videoId date Acquired
movieId title genre length rating
115 1/ 25/ 98 101 The Thirty-Nine Steps
mystery 101 PG
90987 2/ 5/ 97 450 Elizabeth costume drama 123 PG-13 145 12/ 31/ 95 145 Lady and the Tramp animated drama 93 G 8034 4/ 5/ 98 145 Lady and the Tramp animated drama 93 G 90988 4/ 5/ 98 450 Elizabeth costume drama 123 PG-13 90989 3/ 25/ 86 450 Elizabeth costume drama 123 PG-13 543 5/ 12/ 95 101 The Thirty-Nine
Steps mystery 101 R
1243 4/ 29/ 91 123 Annie Hall romantic comedy 110 R
⢠Anomalies occur when data is inconsistently updated⢠Redundancy of values is the source of anomalies⢠Update anomalies are of three types:
â Modificationâ Deletionâ Insertion
43
Redundancy and Anomalies in Relation Schemas
Update Anomalies:⢠Modification anomaly caused, for example, by changing title, genre, length or rating in any one or two
(but not all three) of the green-highlighted rowsâ Information about same movie is different in different records (i.e. it is inconsistent)
⢠Deletion anomaly caused by deletion of row with videoId1243 (pink)â Information about movie is deleted along with video
⢠Insertion anomaly caused by last row (blue)â Length and rating are inconsistent with other rows
videoId date Acquired
movieId title genre length rating
115 1/ 25/ 98 101 The Thirty-Nine Steps
mystery 101 PG
90987 2/ 5/ 97 450 Elizabeth costume drama 123 PG-13 145 12/ 31/ 95 145 Lady and the Tramp animated drama 93 G 8034 4/ 5/ 98 145 Lady and the Tramp animated drama 93 G 90988 4/ 5/ 98 450 Elizabeth costume drama 123 PG-13 90989 3/ 25/ 86 450 Elizabeth costume drama 123 PG-13 543 5/ 12/ 95 101 The Thirty-Nine
Steps mystery 101 R
1243 4/ 29/ 91 123 Annie Hall romantic comedy 110 R 114 6/ 5/ 98 450 Elizabeth costume drama 110 R
44
Functional Dependencies Between Attributes
⢠A functional dependency is a strong connection between two or more attributes in a table. â one attribute is functionally dependent on another attribute when
any two rows of the table that have the same value of the second attribute must have the same value for the first
⢠Example: movieId determines title, genre, length, ratingâ Each row with movieId 123 has the same values for other
attributesâ FD2: movieId {title, genre, length, rating}
VideoMovie:(videoId, dateAcquired, movieId, title, genre, length, rating)
FD2
movieId determines the values of the pointed attributes
pointed attributes are dependent on movieId
Thus, we have four attributes functionally dependent on movieId
45
Primary Keys
⢠Primary Keys define a kind of Constraintâ Non-nullâ Unique
⢠Primary Keys define a kind of Functional Dependencyâ Primary key value uniquely identifies an entityâ The total of all other attributes of an entity is dependent on the
entityâs unique identifier (i.e. the entityâs Primary Key)
⢠Constraints are, thus, Functional Dependencies.
46
Normalization⢠Normalization is the process of transforming some
objects into a structural form that satisfies some collection of rules
⢠Any schema that is in normal form is guaranteed to have certain quality characteristics
⢠Each normal form has a rule that describes what kinds of functional dependencies the normal form allows. â Normalization is the process of transforming schemas in order to
remove violations of the normal form rules. â Normalization is applied independently to each relation schema in a
database schema. â A a database schema is said to be in normal form if each of its relation
schemas is in the normal form.
47
Normalization: Introduction⢠A process for designing âgoodâ table structures⢠Good structures:
â Avoid data redundancy and inconsistenciesâ Insure that all data can be retrieved (no orphans)â Facilitate updates (information is stored only once)â Ensure that up-to-date information can readily be accessed by all users
48Project Design Sample: Rob, Database Systems,Course Technology, 2002, p 177-187
Original LayoutPrior to Normalization
Proj_Num Proj_Name Emp_Num Emp_Name Job_Class Chg_Hour Hours
15 Evergreen 103 June A. Elect.Eng. 84.50 23.8101 Jon G. Dat Des. 105.00 19.4105 Alice K. Dat. Des. 105.00 35.7
18 Amber 114 Ann J. App Eng. 48.10 24.6101 John G. Dat Des. 105.00 14.5
Null Primary Key
Duplicate & Inconsistent Data
Repeating Groups Note that an employee can be assigned to multiple projects; and that to any project multiple employees can be assigned.
49
Convert to 3NF⢠Remove all fields from the 2NF table that depend on
another non-key field, and place those fields in a new table that uses the non-key field as a primary key.
⢠E.g. Chg_Hour depends on Job_Class; so move those fields to new table JOB with primary key, Job_Code.
Job_Class Chg_HourEMPLOYEE Table JOB Table
50
Proj_NumProj_Name
Emp_NumEmp_Fnam
Assgn_NumProj_Num Assgn_Date
PROJECT Table
EMPLOYEE Table
ASSIGN Table
After Phase 3 Normalization(3rd Normal Form)
Isolate Transitive (Indirect) Dependencies. (JOB Table still in 2NF)
Emp_Num(Project Leader)
Job_Code Job_Desc(Job_Class)
JOB TableJob_Chg_Hr
Emp_Lnam Emp_Hire_Date Job_Code
Emp_Num Assgn_Hrs Assgn_Chg_Hr
Transitive Dependency desired for historical accuracy of costs.
Non-key Field
Primary Key
Foreign Key
51
Chapter 8Manipulating Database Content
with Relational Algebra and Microsoft Access
IV. Manipulate Relational Data
52
Chapter 9Using SQL to Manipulate
Database Content and Structure
53
Using SQL to Manipulate Database Content and Structure
⢠How to create queries in SQL â Simple select statements â Simple join queriesâ Outer join queriesâ Queries with multiple relational operatorsâ String pattern matching and ordering resultsâ Expressions, literals, and aggregates â Group by and having clausesâ Nested select statementsâ Set operations
⢠How to Modify database content with SQL â Insert statementsâ Update statementsâ Delete statements
⢠How to Create and manipulate table definitions with SQLâ Creating tables and defining attributes â Key and foreign key constraint specificationsâ Default values, nulls, and constraintsâ Adding, removing, and modifying attributesâ Schemas and user ids â Drop statements
⢠SQL statements for bighit online video sales
54
Simple select statements⢠Select statement in SQL combines many relational
operationsâ select <attribute names> from <tables> where <condition>
⢠select clause â specifies the attributes that go in the results table.
⢠from clause â specifies the source tables that the database will access in order
to execute the query.
⢠where clause â specifies the selection conditions, including the join condition
55
Examples of Simple Select Statements
⢠Examplesâ Project Customer on lastName, firstName with duplicates
⢠select lastName, firstName from Customer â Project Customer on lastName, firstName without duplicates
⢠select distinct lastName, firstName from Customerâ select from Customer where lastName = âDoeâ
⢠select * from Customer where lastName = 'Doe'
⢠Notice the use of string literals with single quotesâ âDoeâ
56
Simple join queries⢠Example join operation
â join Employee and TimeCard where Employee.ssn = TimeCard.ssn
⢠Two forms of joinâ select * from Employee, TimeCard
where Employee.ssn = TimeCard.ssnâ select * from Employee join TimeCard
on Employee.ssn = TimeCard.ssn
57
Having clause to restrict outputs⢠Having clause selects groups to produce output rows
â A group produces an output row only if having condition is trueâ select title, genre, count(*) as numRentals,
avg(cost) as average, sum(cost) as sumfrom Movie, Video, PreviousRentalwhere Movie.movieId = Video.movieId and Video.videoId = PreviousRental.videoIdgroup by Movie.movieId, title, genrehaving count(*)>1
⢠A group with count(*) [number of rows in group] <=1 does not produce an output row
Title Genre numRentals average sum
Annie Hall comedy 4 $2.37 $9.46
The Thirty-nine Steps mystery 2 $2.49 $4.98
No simple attribute can appear in the
select clause unless it also appears in the
group by clause
58
Modify database content⢠Insert statement adds new rows to a table⢠Update statement modifies one or more attributes of
specified rows of a table⢠Delete statement deletes one or more rows from a
table
59
Chapter 10Presenting Information on the Web
with HTML
V. Create Interactive Web Sites
60
Chapter 11Creating Interaction between Users
and Servers with ASP and JavaScript
61
Architecture of Dynamic Web Sites
Web browser
Files
Browser computer Web server computer
Httpserver
2. Browsercollects data andsends request toWeb server
4. Applicationprocessor fetchesprogram from file
1: Userenters dataand clicks abutton
7. Browser formatsHTML document anddisplays it.
WebApplicationprocessor
6. Application programprocesses data andgenerates new HTMLdocument
3. Web serversends request toWeb applicationprocessor
Applicationprogram
5. Application programbegins execution andreads user data
62
Designing HTML Forms for User Input
⢠An HTML form (source code) allows user inputâ Input fields are defined by input tagsâ E.g. <input type=âtextâ name=âaccountIdâ>
⢠A form is defined by a form tagâ <form method="GET" action="newcustomer.asp"> â method attribute is âGETâ or âPUTâ (More about this later)â action attribute is the URL of the program that will process the form
submission⢠Text input fields defined by type=âtextâ
â <input type=âtextâ size=â20â name=âfirstNameâ>â <input type=âtextâ size=â20â name=âlastNameâ>
⢠Buttons defined by type=âsubmitâ and type=âresetââ <input type="submit" value="Add my information"> â <input type="reset">
⢠When user clicks submitâ Values of all form fields are collected and sent to the Web server referenced
by the action attribute of the form tag
63
Understanding Browser-Server Interaction with HTTP
⢠Hypertext Transfer Protocol (HTTP) is a strategy for browser-server interactionâ Defines how the browser tells the server what is needed
⢠HTTP supports two methods: GET and POSTâ GET puts form contents into the URLâ POST transmits form contents as a separate operationâ Both methods provide the same information to the server
⢠Both methods represent form contents the same way â Query string: a sequence of name=value pairs with & separationâ Encoded to replace blanks and special charactersâ firstName=Janet&lastName=Mylopoulos&street=4402+Elm+St.&city=Apopka
&state=FL&zipcode=3345 â Other symbols, e.g. ? + & are encoded by percent sign plus 2-digit
hexadecimal number⢠+ as %2b ⢠& as %26
64
Writing Web Applications in ASP and JavaScript
⢠A Web application runs as a request within a Web Serverâ Internet Information Server (IIS) is a Web server for Windows
⢠IIS is distributed as part of the Windows NT, Windows 2000, and Windows XP professional operating systems
â IIS supports Active Server Pages (ASP), an application processor that knows how to run Web applications
⢠ASP is also a language for writing Web applications ⢠An ASP Web application is a file
Web browser
Files
Browser computer Web server computer
IIS WebServer
ASPProcessor
ASP scriptexecution
65
Processing Forms with ASP and JavaScript
⢠ASP script receives request variables in Request objectâ fName = Request("firstName");â JavaScript variable fName is assigned the value of the request variable
firstName⢠Basic strategy for ASP program
â Get values of request variables and assign to JavaScript variablesâ Process values as necessaryâ Output result information to HTML output
⢠Example script to print firstNameâ <%@LANGUAGE="JavaScript"%> <html>
<% var fName=Request(âfirstNameâ);%><h2> <%=fName%> </h2></html>
⢠See the code in action with form simplestform.html or URLâ http://www.web4data.com/dbmgmt/bighit/simplest.asp?firstName=Joe
66
Chapter 12Developing Database Applications
for the Web
67
Connecting to Database with Windows
⢠ODBC (Open Database Connectivity) is the Windows protocol for client-server interaction
⢠Add an Access database to ODBC on the Web server computerâ Open ODBC Data Source Administratorâ Add the Access database file to the
System Data Source Name (DSN) list⢠Once the database is a registered
data sourceâ ASP application can use the database
⢠ODBC also supports interaction with databases on remote computers
68
Connecting to a Database with ASP and JavaScript
⢠Object class Connection supports connecting to database⢠ASP script must create a Connection object and execute itâs
Open methodâ conn = Server.CreateObject("ADODB.Connection");â conn.Open("bighitmdb"); // argument is DSN name of database
⢠Each script that interacts with database begins by creating and opening a Connection object
⢠The method call Server.CreateObject("ADODB.Connection")â Asks the Server object to create an object of type ADODB.Connectionâ ADODB (ActiveX Data Object Database) is a collection of classes and
objects that support database access from Windows applications⢠Now we are ready to use the Connection object to access the
database
69
Fetching and Displaying the Customerâs Name
⢠Code to get customer nameâ conn = Server.CreateObject("ADODB.Connection"); conn.Open("bighitmdb");
accountId = Request.QueryString("accountID"); // construct SQL query to fetch customer name customerQuery = "select lastName, firstName from Customer" + " where accountId = "+accountId; // execute the query customer = conn.Execute(customerQuery); // get the first and last names from the query result name = customer("firstName")+" "+customer("lastName"); customer.close(); printHeader("Outstanding Rentals","for customer "+name);
⢠Special items includeâ Creation of SQL statement using request variable accountId â conn.Execute to execute the SQL query and get a result backâ customer(âfirstNameâ) to fetch value of firstName attribute