69
1 Database Programming Summary John Lamertina Reference: Riccardi, G, Database Management with Web Site Development Applications , Addison-Wesley, 2003

Database Programming Summary

  • Upload
    fleta

  • View
    39

  • Download
    0

Embed Size (px)

DESCRIPTION

Database Programming Summary. John Lamertina. Reference: Riccardi, G, Database Management with Web Site Development Applications , Addison-Wesley, 2003. Content. Part I: Introduction Chapters 1 and 2 Part II: Design Information Systems Chapters 3 and 4 - PowerPoint PPT Presentation

Citation preview

Page 1: Database Programming Summary

1

Database Programming Summary

John Lamertina

Reference: Riccardi, G, Database Management with Web Site Development Applications, Addison-Wesley, 2003

Page 2: Database Programming Summary

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

Page 3: Database Programming Summary

3

Chapter 1Introduction to Information and

Database Systems

I. Introduction

Page 4: Database Programming Summary

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

Page 5: Database Programming Summary

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

Page 6: Database Programming Summary

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))

Page 7: Database Programming Summary

7

Chapter 2Internet Information Systems

Page 8: Database Programming Summary

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

Page 9: Database Programming Summary

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

Page 10: Database Programming Summary

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

Page 11: Database Programming Summary

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'

Page 12: Database Programming Summary

12

Chapter 3Representing Information with

Data Models

II. Design Information Systems

Page 13: Database Programming Summary

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

Page 14: Database Programming Summary

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’

Page 15: Database Programming Summary

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

Page 16: Database Programming Summary

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

Page 17: Database Programming Summary

17

Chapter 4Data Modeling with

Entity-Relationship Diagrams

Page 18: Database Programming Summary

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

Page 19: Database Programming Summary

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

Page 20: Database Programming Summary

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

Page 21: Database Programming Summary

21

Relationship Types• Example of representing relationship type Owns between

classes Store and Video

RelationshipType

EntityClass

RelationshipAttribute

Store VideoOwns

costpurchaseDate

EntityClass

IsOwnedBy

AlternateRelationship

Name

Page 22: Database Programming Summary

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

Page 23: Database Programming Summary

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.

Page 24: Database Programming Summary

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

Page 25: Database Programming Summary

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.

Page 26: Database Programming Summary

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

Page 27: Database Programming Summary

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.

Page 28: Database Programming Summary

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.

Page 29: Database Programming Summary

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

Page 30: Database Programming Summary

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.

Page 31: Database Programming Summary

31

Chapter 5Defining Relational Data Models

III. Design Relational Databases

Page 32: Database Programming Summary

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

Page 33: Database Programming Summary

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

Page 34: Database Programming Summary

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

Page 35: Database Programming Summary

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.

Page 36: Database Programming Summary

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

Page 37: Database Programming Summary

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.

Page 38: Database Programming Summary

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

Page 39: Database Programming Summary

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)

Page 40: Database Programming Summary

40

Chapter 6Defining Relational Databases with

Microsoft Access

Page 41: Database Programming Summary

41

Chapter 7Improving Relational Schemas and

Normalization

Page 42: Database Programming Summary

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

Page 43: Database Programming Summary

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

Page 44: Database Programming Summary

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

Page 45: Database Programming Summary

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.

Page 46: Database Programming Summary

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.

Page 47: Database Programming Summary

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

Page 48: Database Programming Summary

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.

Page 49: Database Programming Summary

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

Page 50: Database Programming Summary

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

Page 51: Database Programming Summary

51

Chapter 8Manipulating Database Content

with Relational Algebra and Microsoft Access

IV. Manipulate Relational Data

Page 52: Database Programming Summary

52

Chapter 9Using SQL to Manipulate

Database Content and Structure

Page 53: Database Programming Summary

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

Page 54: Database Programming Summary

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

Page 55: Database Programming Summary

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’

Page 56: Database Programming Summary

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

Page 57: Database Programming Summary

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

Page 58: Database Programming Summary

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

Page 59: Database Programming Summary

59

Chapter 10Presenting Information on the Web

with HTML

V. Create Interactive Web Sites

Page 60: Database Programming Summary

60

Chapter 11Creating Interaction between Users

and Servers with ASP and JavaScript

Page 61: Database Programming Summary

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

Page 62: Database Programming Summary

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

Page 63: Database Programming Summary

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

Page 64: Database Programming Summary

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

Page 65: Database Programming Summary

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

Page 66: Database Programming Summary

66

Chapter 12Developing Database Applications

for the Web

Page 67: Database Programming Summary

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

Page 68: Database Programming Summary

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

Page 69: Database Programming Summary

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