0% found this document useful (0 votes)
196 views37 pages

DBMS - Module 3

This document contains notes on advanced SQL queries, database application development, and internet applications. It discusses more complex SQL queries including comparisons involving NULL values, nested queries, and correlated nested queries. It provides examples of using logical connectives, comparison operators like IN and EXISTS, and formulating queries with nested subqueries. It also briefly mentions database application development topics like JDBC, stored procedures, and the three-tier application architecture for internet applications.

Uploaded by

yibojek511
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
196 views37 pages

DBMS - Module 3

This document contains notes on advanced SQL queries, database application development, and internet applications. It discusses more complex SQL queries including comparisons involving NULL values, nested queries, and correlated nested queries. It provides examples of using logical connectives, comparison operators like IN and EXISTS, and formulating queries with nested subqueries. It also briefly mentions database application development topics like JDBC, stored procedures, and the three-tier application architecture for internet applications.

Uploaded by

yibojek511
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

18CS53 Module 3 DBMS Notes

SQL: Advances Queries: More complex SQL retrieval queries, Specifying constraints as
assertions and action triggers, Views in SQL, Schema change statements in SQL.
Database Application Development: Accessing databases from applications, An introduction
to JDBC, JDBC classes and interfaces, SQLJ, Stored procedures, Case study: The internet
Bookshop.
Internet Applications: The three-Tier application architecture, the presentation layer, The
Middle Tier.

3.1 More Complex SQL Retrieval Queries


3.1.1 Comparisons Involving NULL and Three-Valued Logic

SQL has various rules for dealing with NULL values. NULL is used to represent a missing value,
but that it usually has one of three different interpretations—value unknown (value exists but is
not known, or it is not known whether or not the value exists), value not available (value exists
but is purposely withheld), or value not applicable (the attribute does not apply to this tuple or is
undefined for this tuple). Consider the following examples to illustrate each of the meanings of
NULL.

1. Unknown value. A person’s date of birth is not known, so it is represented by NULL in


the database. An example of the other case of unknown would be NULL for a person’s
home phone because it is not known whether or not the person has a home phone.
2. Unavailable or withheld value. A person has a home phone but does not want it to be
listed, so it is withheld and represented as NULL in the database.
3. Not applicable attribute. An attribute LastCollegeDegree would be NULL for a person
who has no college degrees because it does not apply to that person.

It is often not possible to determine which of the meanings is intended; for example, a NULL for
the home phone of a person can have any of the three meanings. Hence, SQL does not distinguish
among the different meanings of NULL.

In general, each individual NULL value is considered to be different from every other NULL value
in the various database records. When a record with NULL in one of its attributes is involved in a
comparison operation, the result is considered to be UNKNOWN (it may be TRUE or it may be
FALSE). Hence, SQL uses a three-valued logic with values TRUE, FALSE, and UNKNOWN
instead of the standard two-valued (Boolean) logic with values TRUE or FALSE. It is therefore
necessary to define the results (or truth values) of three-valued logical expressions when the logical
connectives AND, OR, and NOT are used. Table 3.1 shows the resulting values.

Table 3.1 Logical Connectives in Three-Valued Logic

Dept. of CSE, HKBKCE Page 1


18CS53 Module 3 DBMS Notes
In Tables 3.1(a) and 3.1(b), the rows and columns represent the values of the results of comparison
conditions, which would typically appear in the WHERE clause of an SQL query. Each expression
result would have a value of TRUE, FALSE, or UNKNOWN. The result of combining the two
values using the AND logical connective is shown by the entries in Table 3.1(a). Table 3.1(b)
shows the result of using the OR logical connective.

For example, the result of (FALSE AND UNKNOWN) is FALSE, whereas the result of (FALSE
OR UNKNOWN) is UNKNOWN. Table 3.1(c) shows the result of the NOT logical operation.
Notice that in standard Boolean logic, only TRUE or FALSE values are permitted; there is no
UNKNOWN value.

Query 1. Retrieve the names of all employees who do not have supervisors.
SELECT Fname, Lname
FROM EMPLOYEE
WHERE Super_ssn IS NULL;

3.1.2 Nested Queries, Tuples, and Set/Multiset Comparisons


Some queries require that existing values in the database be fetched and then used in a comparison
condition. Such queries can be conveniently formulated by using nested queries, which are
complete select-from-where blocks within another SQL query. That other query is called the outer
query. These nested queries can also appear in the WHERE clause or the FROM clause or the
SELECT clause or other SQL clauses as needed. Q2A introduces the comparison operator IN,
which compares a value v with a set (or multiset) of values V and evaluates to TRUE if v is one of
the elements in V.

In Q2A, the first nested query selects the project numbers of projects that have an employee with
last name ‘Smith’ involved as manager, whereas the second nested query selects the project
numbers of projects that have an employee with last name ‘Smith’ involved as worker. In the outer
query, we use the OR logical connective to retrieve a PROJECT tuple if the PNUMBER value of
that tuple is in the result of either nested query.

Q2A: SELECT DISTINCT Pnumber


FROM PROJECT
WHERE Pnumber IN
( SELECT Pnumber
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE Dnum = Dnumber AND Mgr_ssn = Ssn AND Lname =‘Smith’ )

OR

Pnumber IN
( SELECT Pno
FROM WORKS_ON, EMPLOYEE
WHERE Essn = Ssn AND Lname = ‘Smith’ );

If a nested query returns a single attribute and a single tuple, the query result will be a single
(scalar) value. In such cases, it is permissible to use = instead of IN for the comparison operator.
In addition to the IN operator, a number of other comparison operators can be used to compare a
single value v (typically an attribute name) to a set or multiset v (typically a nested query).

Dept. of CSE, HKBKCE Page 2


18CS53 Module 3 DBMS Notes
An example is the following query, which returns the names of employees whose salary is greater
than the salary of all the employees in department 5:

SELECT Lname, Fname


FROM EMPLOYEE
WHERE Salary > ALL ( SELECT Salary
FROM EMPLOYEE
WHERE Dno = 5 );

In general, we can have several levels of nested queries. We can once again be faced with possible
ambiguity among attribute names if attributes of the same name exist—one in a relation in the
FROM clause of the outer query, and another in a relation in the FROM clause of the nested query.
The rule is that a reference to an unqualified attribute refers to the relation declared in the
innermost nested query.

Query 3. Retrieve the name of each employee who has a dependent with the same first name and
is the same sex as the employee.
Q3: SELECT E.Fname, E.Lname
FROM EMPLOYEE AS E
WHERE E.Ssn IN ( SELECT D.Essn
FROM DEPENDENT AS D
WHERE E.Fname = D.Dependent_name AND E.Sex = D.Sex );

In the nested query of Q3, we must qualify E.Sex because it refers to the Sex attribute of
EMPLOYEE from the outer query, and DEPENDENT also has an attribute called Sex. If there
were any unqualified references to Sex in the nested query, they would refer to the Sex attribute
of DEPENDENT. However, we would not have to qualify the attributes Fname and Ssn of
EMPLOYEE if they appeared in the nested query because the DEPENDENT relation does not
have attributes called Fname and Ssn, so there is no ambiguity.

3.1.3 Correlated Nested Queries


Whenever a condition in the WHERE clause of a nested query references some attribute of a
relation declared in the outer query, the two queries are said to be correlated. A correlated query
better by considering that the nested query is evaluated once for each tuple (or combination of
tuples) in the outer query. For example, Q3 is as follows: For each EMPLOYEE tuple, evaluate
the nested query, which retrieves the Essn values for all DEPENDENT tuples with the same sex
and name as that EMPLOYEE tuple; if the Ssn value of the EMPLOYEE tuple is in the result of
the nested query, then select that EMPLOYEE tuple.

IN comparison operators can always be expressed as a single block query. For example, Q3 may
be written as in Q4A:

Q4A: SELECT E.Fname, E.Lname


FROM EMPLOYEE AS E, DEPENDENT AS D
WHERE E.Ssn = D.Essn AND E.Sex = D.Sex AND E.Fname = D.Dependent_name;

3.1.4 The EXISTS and UNIQUE Functions in SQL


EXISTS and UNIQUE are Boolean functions that return TRUE or FALSE; hence, they can be
used in a WHERE clause condition. The EXISTS function in SQL is used to check whether the
result of a nested query is empty (contains no tuples) or not.

Dept. of CSE, HKBKCE Page 3


18CS53 Module 3 DBMS Notes
The result of EXISTS is a Boolean value TRUE if the nested query result contains at least one
tuple, or FALSE if the nested query result contains no tuples. We illustrate the use of EXISTS—
and NOT EXISTS—with some examples. First, we formulate Query 3 in an alternative form that
uses EXISTS as in Q4B:

Q4B: SELECT E.Fname, E.Lname


FROM EMPLOYEE AS E
WHERE EXISTS ( SELECT *
FROM DEPENDENT AS D
WHERE E.Ssn = D.Essn AND E.Sex = D.Sex AND E.Fname = D.Dependent_name);

EXISTS and NOT EXISTS are typically used in conjunction with a correlated nested query. Q4B
as follows: For each EMPLOYEE tuple, evaluate the nested query, which retrieves all
DEPENDENT tuples with the same Essn, Sex, and Dependent_name as the EMPLOYEE tuple; if
at least one tuple EXISTS in the result of the nested query, then select that EMPLOYEE tuple.
EXISTS(Q) returns TRUE if there is at least one tuple in the result of the nested query Q, and
returns FALSE otherwise. On the other hand, NOT EXISTS (Q) returns TRUE if there are no
tuples in the result of nested query Q, and returns FALSE otherwise. Next, we illustrate the use of
NOT EXISTS.

Query 5. Retrieve the names of employees who have no dependents.


Q5: SELECT Fname, Lname
FROM EMPLOYEE
WHERE NOT EXISTS ( SELECT *
FROM DEPENDENT
WHERE Ssn = Essn );

In Q5, the correlated nested query retrieves all DEPENDENT tuples related to a particular
EMPLOYEE tuple. If none exist, the EMPLOYEE tuple is selected because the WHERE-clause
condition will evaluate to TRUE in this case. We can explain Q5 as follows: For each
EMPLOYEE tuple, the correlated nested query selects all empty, no dependents are related to the
employee, so we select that EMPLOYEE tuple and retrieve its Fname and Lname.

Query 6. List the names of managers who have at least one dependent.
Q6: SELECT Fname, Lname
FROM EMPLOYEE
WHERE EXISTS ( SELECT *
FROM DEPENDENT
WHERE Ssn = Essn )
AND
EXISTS ( SELECT *
FROM DEPARTMENT
WHERE Ssn = Mgr_ssn );

Query 7A: Retrieve the name of each employee who works on all the projects controlled by
department number 5 can be written using NOT EXISTS in SQL systems.

Q7A: SELECT Fname, Lname


FROM EMPLOYEE
WHERE NOT EXISTS ( ( SELECT Pnumber
FROM PROJECT
WHERE Dnum = 5)

Dept. of CSE, HKBKCE Page 4


18CS53 Module 3 DBMS Notes
EXCEPT ( SELECT Pno
FROM WORKS_ON
WHERE Ssn = Essn) );

In Q7A, the first subquery (which is not correlated with the outer query) selects all projects
controlled by department 5, and the second subquery (which is correlated) selects all projects that
the particular employee being considered works on.

3.1.5 Explicit Sets and Renaming in SQL


It is possible to use an explicit set of values in the WHERE clause, rather than a nested query.
Such a set is enclosed in parentheses in SQL.

Query 8. Retrieve the Social Security numbers of all employees who work on project numbers 1,
2, or 3.
Q8: SELECT DISTINCT Essn
FROM WORKS_ON
WHERE Pno IN (1, 2, 3);

In SQL, it is possible to rename any attribute that appears in the result of a query by adding the
qualifier AS followed by the desired new name. Hence, the AS construct can be used to alias both
attribute and relation names in general, and it can be used in appropriate parts of a query. For
example, Q9A shows how query can be slightly changed to retrieve the last name of each employee
and his or her supervisor while renaming the resulting attribute names as Employee_name and
Supervisor_name. The new names will appear as column headers for the query result.

Q9A: SELECT E.Lname AS Employee_name, S.Lname AS Supervisor_name


FROM EMPLOYEE AS E, EMPLOYEE AS S
WHERE E.Super_ssn = S.Ssn;

3.1.6 Joined Tables in SQL and Outer Joins

The concept of a joined table (or joined relation) was incorporated into SQL to permit users to
specify a table resulting from a join operation in the FROM clause of a query. This construct may
be easier to comprehend than mixing together all the select and join conditions in the WHERE
clause. For example, consider query Q10, which retrieves the name and address of every employee
who works for the ‘Research’ department. It may be easier to specify the join of the EMPLOYEE
and DEPARTMENT relations in the WHERE clause, and then to select the desired tuples and
attributes. This can be written in SQL as in Q10A:

Q10A: SELECT Fname, Lname, Address


FROM (EMPLOYEE JOIN DEPARTMENT ON Dno = Dnumber)
WHERE Dname = ‘Research’;

The FROM clause in Q10A contains a single joined table. The attributes of such a table are all the
attributes of the first table, EMPLOYEE, followed by all the attributes of the second table,
DEPARTMENT. The concept of a joined table also allows the user to specify different types of
join, such as NATURAL JOIN and various types of OUTER JOIN. In a NATURAL JOIN on two
relations R and S, no join condition is specified; an implicit EQUIJOIN condition for each pair of
attributes with the same name from R and S is created.

This is illustrated in Q10B, where the DEPARTMENT relation is renamed as DEPT and its
attributes are renamed as Dname, Dno (to match the name of the desired join attribute Dno in the

Dept. of CSE, HKBKCE Page 5


18CS53 Module 3 DBMS Notes
EMPLOYEE table), Mssn, and Msdate. The implied join condition for this NATURAL JOIN is
EMPLOYEE.Dno = DEPT.Dno, because this is the only pair of attributes with the same name
after renaming:

Q10B: SELECT Fname, Lname, Address


FROM (EMPLOYEE NATURAL JOIN
(DEPARTMENT AS DEPT (Dname, Dno, Mssn, Msdate)))
WHERE Dname = ‘Research’;

The default type of join in a joined table is called an inner join, where a tuple is included in the
result only if a matching tuple exists in the other relation. For example, If the user requires that all
employees be included, a different type of join called OUTER JOIN must be used explicitly.
There are several variations of OUTER JOIN. In the SQL standard, this is handled by explicitly
specifying the keyword OUTER JOIN in a joined table, as illustrated in Q11B:

Q11B: SELECT E.Lname AS Employee_name, S.Lname AS Supervisor_name


FROM (EMPLOYEE AS E LEFT OUTER JOIN EMPLOYEE AS S
ON E.Super_ssn = S.Ssn);

In SQL, the options available for specifying joined tables include INNER JOIN, LEFT OUTER
JOIN, RIGHT OUTER JOIN, and FULL OUTER JOIN. The keyword CROSS JOIN is used to
specify the CARTESIAN PRODUCT operation, although this should be used only with the utmost
care because it generates all possible tuple combinations. It is also possible to nest join
specifications; that is, one of the tables in a join may itself be a joined table. This allows the
specification of the join of three or more tables as a single joined table, which is called a multiway
join.

For example, Q12A is a different way of specifying query Q2 from Section 6.3.1 using the concept
of a joined table:
Q12A: SELECT Pnumber, Dnum, Lname, Address, Bdate
FROM ((PROJECT JOIN DEPARTMENT ON Dnum = Dnumber)
JOIN EMPLOYEE ON Mgr_ssn = Ssn)
WHERE Plocation = ‘Stafford’;

3.1.7 Aggregate Functions in SQL


Aggregate functions are used to summarize information from multiple tuples into a single-tuple
summary. Grouping is used to create subgroups of tuples before summarization. Grouping and
aggregation are required in many database of built-in aggregate functions exist: COUNT, SUM,
MAX, MIN, and AVG. The COUNT function returns the number of tuples or values as specified
in a query.

The functions SUM, MAX, MIN, and AVG can be applied to a set or multiset of numeric values
and return, respectively, the sum, maximum value, minimum value, and average (mean) of those
values. These functions can be used in the SELECT clause or in a HAVING clause (which we
introduce later). The functions MAX and MIN can also be used with attributes that have
nonnumeric domains if the domain values have a total ordering among one another. We illustrate
the use of these functions with several queries.

Query 13. Find the sum of the salaries of all employees, the maximum salary, the minimum salary,
and the average salary.
Q13: SELECT SUM (Salary), MAX (Salary), MIN (Salary), AVG (Salary)
FROM EMPLOYEE;

Dept. of CSE, HKBKCE Page 6


18CS53 Module 3 DBMS Notes
This query returns a single-row summary of all the rows in the EMPLOYEE table. We could use
AS to rename the column names in the resulting single-row table; for example, as in Q13A.
Q13A: SELECT SUM (Salary) AS Total_Sal, MAX (Salary) AS Highest_Sal,
MIN (Salary) AS Lowest_Sal, AVG (Salary) AS Average_Sal
FROM EMPLOYEE;

If we want to get the preceding aggregate function values for employees of a specific department—
say, the ‘Research’ department—we can write Query 14, where the EMPLOYEE tuples are
restricted by the WHERE clause to those employees who work for the ‘Research’ department.

Query 14. Find the sum of the salaries of all employees of the ‘Research’ department, as well as
the maximum salary, the minimum salary, and the average salary in this department.
Q14: SELECT SUM (Salary), MAX (Salary), MIN (Salary), AVG (Salary)
FROM (EMPLOYEE JOIN DEPARTMENT ON Dno = Dnumber)
WHERE Dname = ‘Research’;

Queries 15 and 16. Retrieve the total number of employees in the company (Q15) and the number
of employees in the ‘Research’ department (Q16).

Q15: SELECT COUNT (*)


FROM EMPLOYEE;

Q16: SELECT COUNT (*)


FROM EMPLOYEE, DEPARTMENT
WHERE DNO = DNUMBER AND DNAME = ‘Research’;

Here the asterisk (*) refers to the rows (tuples), so COUNT (*) returns the number of rows in the
result of the query. We may also use the COUNT function to count values in a column rather than
tuples, as in the next example.

Query 17. Count the number of distinct salary values in the database.
Q17: SELECT COUNT (DISTINCT Salary)
FROM EMPLOYEE;

If we write COUNT (SALARY) instead of COUNT (DISTINCT SALARY) in Q17, then duplicate
values will not be eliminated. However, any tuples with NULL for SALARY will not be counted.
In general, NULL values are discarded when aggregate functions are applied to a particular
column (attribute); the only exception is for COUNT (*) because tuples instead of values are
counted. In the previous examples, any Salary values that are NULL are not included in the
aggregate function calculation.

The general rule is as follows: when an aggregate function is applied to a collection of values,
NULLs are removed from the collection before the calculation; if the collection becomes empty
because all values are NULL, the aggregate function will return NULL.

3.1.8 Grouping: The GROUP BY and HAVING Clauses


In many cases we want to apply the aggregate functions to subgroups of tuples in a relation, where
the subgroups are based on some attribute values. For example, we may want to find the average
salary of employees in each department or the number of employees who work on each project.
In these cases we need to partition the relation into nonoverlapping subsets (or groups) of tuples.
Each group (partition) will consist of the tuples that have the same value of some attribute(s),
called the grouping attribute(s).

Dept. of CSE, HKBKCE Page 7


18CS53 Module 3 DBMS Notes

SQL has a GROUP BY clause for this purpose. The GROUP BY clause specifies the grouping
attributes, which should also appear in the SELECT clause, so that the value resulting from
applying each aggregate function to a group of tuples appears along with the value of the grouping
attribute(s).

Query 18. For each department, retrieve the department number, the number of employees in the
department, and their average salary.
Q18: SELECT Dno, COUNT (*), AVG (Salary)
FROM EMPLOYEE
GROUP BY Dno;

In Q18, the EMPLOYEE tuples are partitioned into groups—each group having the same value
for the GROUP BY attribute Dno. Hence, each group contains the employees who work in the
same department. The COUNT and AVG functions are applied to each such group of tuples.
Notice that the SELECT clause includes only the grouping attribute and the aggregate functions
to be applied on each group of tuples.

Figure 3.2(a) illustrates how grouping works and shows the result of Q18.

Sometimes we want to retrieve the values of these functions only for groups that satisfy certain
conditions. For example, suppose that we want the projects with more than two employees appear
in the result. SQL provides a HAVING clause, which can appear in conjunction with a GROUP
BY clause, for this purpose. HAVING provides a condition on the summary information regarding
the group of tuples associated with each value of the grouping attributes. Only the groups that
satisfy the condition are retrieved in the result of the query. This is illustrated by Query 18’.

Query 18’. For each project on which more than two employees work, retrieve the project number,
the project name, and the number of employees who work on the project.
Q18`: SELECT Pnumber, Pname, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE Pnumber = Pno
GROUP BY Pnumber, Pname
HAVING COUNT (*) > 2;

Notice that although selection conditions in the WHERE clause limit the tuples to which functions
are applied, the HAVING clause serves to choose whole groups. Figure 3.2(b) illustrates the use
of HAVING and displays the result of Q18`.

Dept. of CSE, HKBKCE Page 8


18CS53 Module 3 DBMS Notes

Figure 3.2(b): The use of HAVING and displays the result of Q18`.

Query 19. For each department that has more than five employees, retrieve the department number
and the number of its employees who are making more than $40,000.
Q19: SELECT Dno, COUNT (*)
FROM EMPLOYEE
WHERE Salary>40000 AND Dno IN
( SELECT Dno
FROM EMPLOYEE
GROUP BY Dno
HAVING COUNT (*) > 5)
GROUP BY Dno;

3.1.9 Other SQL Constructs: WITH and CASE


The WITH clause allows a user to define a table that will only be used in a particular query; it is
somewhat similar to creating a view that will be used only in one query and then dropped. This
construct was introduced as a convenience in SQL:99 and may not be available in all SQL based
DBMSs. Queries using WITH can generally be written using other SQL constructs. For example,
we can rewrite Q19 as Q19′:

Q19′: WITH BIGDEPTS (Dno) AS


( SELECT Dno
FROM EMPLOYEE
GROUP BY Dno
HAVING COUNT (*) > 5)
SELECT Dno, COUNT (*)
FROM EMPLOYEE
WHERE Salary>40000 AND Dno IN BIGDEPTS
GROUP BY Dno;

In Q19′, we defined in the WITH clause a temporary table BIG_DEPTS whose result holds the
Dno’s of departments with more than five employees, then used this table in the subsequent query.
Once this query is executed, the temporary table BIGDEPTS is discarded. SQL also has a CASE
construct, which can be used when a value can be different based on certain conditions. This can
be used in any part of an SQL query where a value is expected, including when querying, inserting
or updating tuples.
Dept. of CSE, HKBKCE Page 9
18CS53 Module 3 DBMS Notes

Query 20: Suppose we want to give employees different raise amounts depending on which
department they work for; for example, employees in department 5 get a $2,000 raise, those in
department 4 get $1,500 and those in department 1 get $3,000. Then we could re-write the update
operation:

UPDATE EMPLOYEE
SET Salary =
CASE WHEN Dno = 5 THEN Salary + 2000
WHEN Dno = 4 THEN Salary + 1500
WHEN Dno = 1 THEN Salary + 3000
ELSE Salary + 0;

3.1.10 Recursive Queries in SQL


A recursive relationship between tuples of the same type is the relationship between an employee
and a supervisor. This relationship is described by the foreign key Super_ssn of the EMPLOYEE
relation, and it relates each employee tuple (in the role of supervisee) to another employee tuple
(in the role of supervisor).

Query 21: Retrieve all supervisees of a supervisory employee e at all levels—that is, all employees
e′ directly supervised by e, all employees e′ directly supervised by each employee e′, all employees
e″′ directly supervised by each employee e″, and so on.
Q21: WITH RECURSIVE SUP_EMP (SupSsn, EmpSsn) AS ( SELECT SupervisorSsn, Ssn
FROM EMPLOYEE
UNION
SELECT E.Ssn, S.SupSsn
FROM EMPLOYEE AS E, SUP_EMP AS S
WHERE E.SupervisorSsn = S.EmpSsn)
SELECT*
FROM SUP_EMP;

In Q21, we are defining a view SUP_EMP that will hold the result of the recursive query. The
view is initially empty. It is first loaded with the first level (supervisor,supervisee) Ssn
combinations via the first part (SELECT SupervisorSss, Ssn FROM EMPLOYEE), which is
called the base query. This will be combined via UNION with each successive level of supervisees
through the second part, where the view contents are joined again with the base values to get the
second level combinations, which are UNIONed with the first level. This is repeated with
successive levels until a fixed point is reached, where no more tuples are added to the view. At
this point, the result of the recursive query is in the view SUP_EMP.

3.2 Specifying Constraints as Assertions and Actions as Triggers


The two additional features of SQL: the CREATE ASSERTION statement and the CREATE
TRIGGER statement.

3.2.1 Specifying General Constraints as Assertions in SQL


CREATE ASSERTION, which can be used to specify additional types of constraints that are
outside the scope of the built-in relational model constraints (primary and unique keys, entity
integrity, and referential integrity) .These built-in constraints, can be specified within the
CREATE TABLE statement of SQL. In SQL, users can specify general constraints—those that
do not fall into any of the categories via declarative assertions, using the CREATE
ASSERTION statement. Each assertion is given a constraint name and is specified via a condition
similar to the WHERE clause of an SQL query.

Dept. of CSE, HKBKCE Page 10


18CS53 Module 3 DBMS Notes

For example, to specify the constraint that the salary of an employee must not be greater than
the salary of the manager of the department that the employee works for in SQL, we can write the
following assertion:
CREATE ASSERTION SALARY_CONSTRAINT
CHECK ( NOT EXISTS ( SELECT *
FROM EMPLOYEE E, EMPLOYEE M, DEPARTMENT D
WHERE E.Salary>M.Salary AND E.Dno = D.Dnumber AND D.Mgr_ssn = M.Ssn ) );

3.2.2 Introduction to Triggers in SQL


CREATE TRIGGER, which can be used to specify automatic actions that the database system
will perform when certain events and conditions occur. This type of functionality is generally
referred to as active databases.

For example, suppose we want to check whenever an employee’s salary is greater than the salary
of his or her direct supervisor in the COMPANY database. Several events can trigger this rule:
inserting a new employee record, changing an employee’s salary, or changing an employee’s
supervisor. Suppose that the action to take would be to call an external stored procedure
SALARY_VIOLATION, which will notify the supervisor. The trigger could then be written as in
R5 below. Here we are using the syntax of the Oracle database system.

R5: CREATE TRIGGER SALARY_VIOLATION


BEFORE INSERT OR UPDATE OF SALARY, SUPERVISOR_SSN
ON EMPLOYEE
FOR EACH ROW
WHEN ( NEW.SALARY > ( SELECT SALARY FROM EMPLOYEE
WHERE SSN = NEW.SUPERVISOR_SSN ) )
INFORM_SUPERVISOR(NEW.Supervisor_ssn, NEW.Ssn );

The trigger is given the name SALARY_VIOLATION, which can be used to remove or deactivate
the trigger later. A typical trigger which is regarded as an ECA (Event, Condition, and Action) rule
has three components:
1. The event(s): These are usually database update operations that are explicitly applied to
the database. In this example the events are: inserting a new employee record, changing
an employee’s salary, or changing an employee’s supervisor. The person who writes the
trigger must make sure that all possible events are accounted for. These events are
specified after the keyword BEFORE in our example, which means that the trigger should
be executed before the triggering operation is executed. An alternative is to use the
keyword AFTER, which specifies that the trigger should be executed after the operation
specified in the event is completed.
2. The condition that determines whether the rule action should be executed: Once the
triggering event has occurred, an optional condition may be evaluated. If no condition is
specified, the action will be executed once the event occurs. If a condition is specified, it
is first evaluated, and only if it evaluates to true will the rule action be executed. The
condition is specified in the WHEN clause of the trigger.
3. The action to be taken: The action is usually a sequence of SQL statements, but it could
also be a database transaction or an external program that will be automatically executed.
In this example, the action is to execute the stored procedure INFORM_SUPERVISOR.

Triggers can be used in various applications, such as maintaining database consistency, monitoring
database updates, and updating derived data automatically.

Dept. of CSE, HKBKCE Page 11


18CS53 Module 3 DBMS Notes

3.3 Views (Virtual Tables) in SQL

3.3.1 Concept of a View in SQL


A view in SQL terminology is a single table that is derived from other tables. These other tables
can be base tables or previously defined views. A view does not necessarily exist in physical form;
it is considered to be a virtual table, in contrast to base tables, whose tuples are always physically
stored in the database. This limits the possible update operations that can be applied to views, but
it does not provide any limitations on querying a view.

3.3.2 Specification of Views in SQL


In SQL, the command to specify a view is CREATE VIEW. The view is given a (virtual) table
name (or view name), a list of attribute names, and a query to specify the contents of the view. If
none of the view attributes results from applying functions or arithmetic operations, we do not
have to specify new attribute names for the view, since they would be the same as the names of
the attributes of the defining tables in the default case. The views in V1 and V2 create virtual tables
whose schemas are illustrated in Figure 3.3 when applied to the company database schema.

V1: CREATE VIEW WORKS_ON1 AS SELECT Fname, Lname, Pname, Hours


FROM EMPLOYEE, PROJECT, WORKS_ON
WHERE Ssn = Essn AND Pno = Pnumber;

V2: CREATE VIEW DEPT_INFO(Dept_name, No_of_emps, Total_sal) AS


SELECT Dname, COUNT (*), SUM (Salary)
FROM DEPARTMENT, EMPLOYEE
WHERE Dnumber = Dno
GROUP BY Dname;

Figure 3.3: Two views specified on the database schema.

A view is supposed to be always up-to-date; if we modify the tuples in the base tables on which
the view is defined, the view must automatically reflect these changes. Hence, the view does not
have to be realized or materialized at the time of view definition but rather at the time when we
specify a query on the view. It is the responsibility of the DBMS and not the user to make sure that
the view is kept upto- date. We will discuss various ways the DBMS can utilize to keep a view up-
todate in the next subsection.

If we do not need a view anymore, we can use the DROP VIEW command to dispose of it. For
example, to get rid of the view V1, we can use the SQL statement in V1A:

V1A: DROP VIEW WORKS_ON1;

Dept. of CSE, HKBKCE Page 12


18CS53 Module 3 DBMS Notes
3.3.3 View Implementation, View Update, and Inline Views
The problem of how a DBMS can efficiently implement a view for efficient querying is complex.
Two main approaches have been suggested.
1. One strategy, called query modification, involves modifying or transforming the view
query into a query on the underlying base tables. The disadvantage of this approach is that
it is inefficient for views defined via complex queries that are time-consuming to execute,
especially if multiple view queries are going to be applied to the same view within a short
period of time.
2. The second strategy, called view materialization, involves physically creating a temporary
or permanent view table when the view is first queried or created and keeping that table on
the assumption that other queries on the view will follow. In this case, an efficient strategy
for automatically updating the view table when the base tables are updated must be
developed in order to keep the view up-to-date. Techniques using the concept of
incremental update have been developed for this purpose, where the DBMS can
determine what new tuples must be inserted, deleted, or modified in a materialized view
table when a database update is applied to one of the defining base tables.

Different strategies as to when a materialized view is updated are possible. The immediate update
strategy updates a view as soon as the base tables are changed; the lazy update strategy updates
the view when needed by a view query; and the periodic update strategy updates the view
periodically. A user can always issue a retrieval query against any view. In general, an update on
a view defined on a single table without any aggregate functions can be mapped to an update on
the underlying base table under certain conditions.

For example, consider the WORKS_ON1 view, and suppose that we issue the command to update
the PNAME attribute of ‘John Smith’ from ‘ProductX’ to ‘ProductY’. This view update is shown
in UV1:
UV1: UPDATE WORKS_ON1
SET Pname = ‘ProductY’
WHERE Lname = ‘Smith’ AND Fname = ‘John’ AND Pname = ‘ProductX’;

3.3.4 Views as Authorization Mechanisms


Views can be used to hide certain attributes or tuples from unauthorized users. Suppose a certain
user is only allowed to see employee information for employees who work for department 5; then
we can create the following view DEPT5EMP and grant the user the privilege to query the view
but not the base table EMPLOYEE itself. This user will only be able to retrieve employee
information for employee tuples whose Dno = 5, and will not be able to see other employee tuples
when the view is queried.

CREATE VIEW DEPT5EMP AS


SELECT *
FROM EMPLOYEE
WHERE Dno = 5;

In a similar manner, a view can restrict a user to only see certain columns; for example, only the
first name, last name, and address of an employee may be visible as follows:
CREATE VIEW BASIC_EMP_DATA AS
SELECT Fname, Lname, Address
FROM EMPLOYEE;

Thus by creating an appropriate view and granting certain users access to the view and not the base
tables, they would be restricted to retrieving only the data specified in the view.

Dept. of CSE, HKBKCE Page 13


18CS53 Module 3 DBMS Notes

3.4 Schema Change Statements in SQL


The schema evolution commands available in SQL, which can be used to alter a schema by
adding or dropping tables, attributes, constraints, and other schema elements. This can be done
while the database is operational and does not require recompilation of the database schema.

3.4.1 The DROP Command


The DROP command can be used to drop named schema elements, such as tables, domains, types,
or constraints. One can also drop a whole schema if it is no longer needed by using the DROP
SCHEMA command. There are two drop behavior options: CASCADE and RESTRICT.

For example, to remove the COMPANY database schema and all its tables, domains, and other
elements, the CASCADE option is used as follows:

DROP SCHEMA COMPANY CASCADE;

If the RESTRICT option is chosen in place of CASCADE, the schema is dropped only if it has no
elements in it; otherwise, the DROP command will not be executed. To use the RESTRICT option,
the user must first individually drop each element in the schema, then drop the schema itself.

If a base relation within a schema is no longer needed, the relation and its definition can be deleted
by using the DROP TABLE command. For example, if we no longer wish to keep track of
dependents of employees in the COMPANY database, we can get rid of the DEPENDENT relation
by issuing the following command:

DROP TABLE DEPENDENT CASCADE;

If the RESTRICT option is chosen instead of CASCADE, a table is dropped only if it is not
referenced in any constraints (for example, by foreign key definitions in another relation) or views
or by any other elements. With the CASCADE option, all such constraints, views, and other
elements that reference the table being dropped are also dropped automatically from the schema,
along with the table itself.

Notice that the DROP TABLE command not only deletes all the records in the table if successful,
but also removes the table definition from the catalog. If it is desired to delete only the records but
to leave the table definition for future use, then the DELETE command should be used instead of
DROP TABLE. The DROP command can also be used to drop other types of named schema
elements, such as constraints or domains.

3.4.2 The ALTER Command


The definition of a base table or of other named schema elements can be changed by using the
ALTER command. For base tables, the possible alter table actions include adding or dropping a
column (attribute), changing a column definition, and adding or dropping table constraints. For
example, to add an attribute for keeping track of jobs of employees to the EMPLOYEE base
relation in the COMPANY schema, we can use the command

ALTER TABLE COMPANY.EMPLOYEE ADD COLUMN Job VARCHAR(12);

DATABASE APPLICATION DEVELOPMENT

Applications that rely on the DBMS to manage data run as separate processes that connect to the
DBMS to interact with it. Once a connection is established, SQL commands can be used to insert,

Dept. of CSE, HKBKCE Page 14


18CS53 Module 3 DBMS Notes
delete, and modify data. SQL queries can be used to retrieve desired data. but need to bridge an
important difference in how a database system sees data and how an application program in a
language like Java or C sees data: The result of a database query is a set (or multiset) or records,
hut Java has no set or multiset data type. This mismatch is resolved through additional SQL
constructs that allow applications to obtain a handle on a collection and iterate over the records
one at a time.

Impedance mismatch:
SQL relations are (multi-) sets of records, with no a priori bound on the number of records.
 No such data structure exist traditionally in procedural programming languages such as
C++. (Though now: STL)
 SQL supports a mechanism called a cursor to handle this.

SQL in Application Code


 SQL commands can be called from within a host language (e.g., C++ or Java) program.
 SQL statements can refer to host variables (including special variables used to return
status).
 Must include a statement to connect to the right database.

Two main integration approaches:


1. Embed SQL in the host language (Embedded SQL,SQLJ)
2. Create special API to call SQL commands (JDBC)

 Embedded SQL allows us to access data using static SQL queries in application code with
Dynamic SQL, create the queries at run-time
 Cursors bridge the gap between set-valued query answers and programming languages that
do not support set-values

JDBC, a programming interface that allows us to execute SQL queries from a Java program and
use the results in the Java program. JDBC provides greater portability than Embedded SQL or
Dynamic SQL, and offers the ability to connect to several DBMSs without recompiling the code.

SQLJ, which does the same for static SQL queries, but is easier to program in than Java, with
JDBC. Often, it is useful to execute application code at the database server, rather than just retrieve
data and execute application logic in a separate process.

Stored procedures, which enable application logic to be stored and executed at the database
server.

ACCESSING DATABASES FROM APPLICATIONS


SQL commands can be executed from within a program in a host language such as C or Java. The
use of SQL commands within a host language program is called Embedded SQL.
1. SQL statements (i.e., not declarations) can be used wherever a statement in the host
language is allowed (with a few restrictions).
2. SQL statements must be clearly marked so that a preprocessor can deal with them before
invoking the compiler for the host language.
3. Also, any host language variables used to pass arguments into an SQL command must be
declared in SQL.
4. Some special host language variables must be declared in SQL (so that, for example, any
error conditions arising during SQL execution can be communicated back to the main
application program in the host language).SQLCODE AND SQLSTATE)

Dept. of CSE, HKBKCE Page 15


18CS53 Module 3 DBMS Notes
5. COMPLICATION:-
a. The data types recognized by SQL may not be recognized by the host language and
vice versa.This mismatch is typically addressed by casting data values
appropriately before passing them to or frorn SQL commands.
b. To do with SQL being set-oriented, and is addressed using cursors.

Embedded SQL
Approach: Embed SQL in the host language.
 A preprocessor converts the SQL statements into special API calls.
 Then a regular compiler is used to compile the code.

Language constructs:
 Connecting to a database:
EXEC SQL CONNECT
 Declaring variables:
EXEC SQL BEGIN (END) DECLARE SECTION
 Statements:
EXEC SQL Statement;

Declaring Variables and Exceptions


SQL statements can refer to variables defined in the host program.
Such host language variables must be prefixed by a colon (:) in SQL statements and be declared
between the commands EXEC SQL BEGIN DECLARE SECTION and EXEC SQL END
DECLARE SECTION.

The declarations are similar to how they would look in a C program and, as usual in C. are
separated by semicolons. For example. we can declare variables c-sname, c_sid, c_mt'ing, and
cage (with the initial c used as a naming convention to emphasize that these are host language
variables) as follows:

Declaration:-
EXEC SQL BEGIN DECLARE SECTION
char c_sname[20];
long csid;
short crating;
float cage;
EXEC SQL END DECLARE SECTION

In example, c_snamc has the type CHARACTER(20) when referred to in an SQL statement, csid
has the type INTEGER, crating has the type SMALLINT, and cage has the type REAL.
SQL standard recognizes two special variables for reporting errors, SQLCODE and SQLSTATE.
SQLCODE is the older of the two and is defined to return some negative value when an error
condition arises, the appropriate C type for SQLCODE is long and the appropriate C type for
SQLSTATE is char.

Embedding SQL Statements:- Start with EXEC SQL and write SQL staement :As a simple
example, the following Embedded' SQL statement inserts a row, whose column values based on
the values of the host language variables contained in it, into the Sailors relation:

EXEC SQL
INSERT INTO Sailors VALUES (:c_sname, :csid, :crating, :cage);

Dept. of CSE, HKBKCE Page 16


18CS53 Module 3 DBMS Notes
Observe that a semicolon terminates the command, as per the convention for terminating
statements in C.

Or

EXEC SQL WHENEVER [SQLERROR I NOT FOUND] [ CONTINUE I GOTO st'mt ]


INSERT INTO Sailors VALUES (:c_sname, :csid, :crating, :cage);

For exception handling if error go to stmt else Insert statement execution


 If SQLERROR is specified and the value of SQLSTATE indicates an exception, control is
transferred to stmt, which is presumably responsible for error and exception handling.
 Control is also transferred to stmt if NOT FOUND is specified and the value of SQLSTATE
is 02000, which denotes NODATA.

The SQLSTATE variable should be checked for errors and exceptions after each Embedded SQL
statement.

Cursors:
A major problem in embedding SQL statements in a host language like C is that an impedance
mismatch occurs because SQL operates on set" of records, whereas languages like C do not cleanly
support a set-of-records abstraction.

The solution is to essentially provide a mechanism that allows us to retrieve rows one at a time
from a relation This mechanism is called a cursor.
 Declare a cursor on any relation or on any SQL query (because every query returns a set
of rows).
 Once a cursor is declared, open it (which positions the cursor just before the first row);
fetch the next row; move the cursor (to the next row, to the row after the next n, to the first
row, or to the previous row, etc., by specifying additional parameters for the FETCH
command); or close the cursor.
 Thus, a cursor essentially allows us to retrieve the rows in a table by positioning the cursor
at a particular row and reading its contents.
 INSERT, DELETE, and UPDATE statements typically require no cursor, although some
variants of DELETE and UPDATE use a cursor.

Example-1-without cursor(single row) : As an example, we can find the name and age of a sailor,
specified by assigning a value to the host variable c_sid, declared earlier, as follows:
EXEC SQL SELECT
INTO
FROM
WHERE
S.sname, S.age
:c_sname, :c_age
Sailors S
S.sid = :c_sid;

c_sid C variable .and the INTO clause allows us to assign the columns of the single answer row
to the host variables c_sname and c_age. Therefore, we do not need a cursor to embed this query
in a host language program.

Example-2-using cursor(multiple rows) : The names and ages of all sailors with a rating greater
than the current value of the host variable c_minmting?
Dept. of CSE, HKBKCE Page 17
18CS53 Module 3 DBMS Notes
SELECT S.sname, S.age
FROM Sailors S
WHERE S.rating > :c_minrating
This query returns a collection of rows, not just one row. Embedded in C not give correct result.

The solution is to use a cursor:


DECLARE sinfo CURSOR FOR
SELECT S.sname, S.age
FROM Sailors S
WHERE S.rating > :c_minrating;
This code can be included in a C program, and once it is executed, the cursor sinfo is defined.
Subsequently, we can open the cursor:
OPEN sinfo:

The value of c_minmting in the SQL query associated with the cursor is the value of this variable
when we open the cursor. (The cursor declaration is processed at compile-time, and the OPEN
command is executed at run-time.)
 when a cursor is opened, it is positioned just before the first row.
 Use the FETCH command to read the first row of cursor sinfo into host language variables:

FETCH sinfo INTO :csname, :cage;


 When the FETCH statement is executed, the cursor is positioned to point at the next row
(which is the first row in the table when FETCH is executed for the first time after opening
the cursor) and the column values in the row are copied into the corresponding host
variables.
 By repeatedly executing this FETCH statement (say, in a while-loop in the C program),read
all the rows computed by the query, one row at a time.

When we are done with a cursor, we can close it:


CLOSE sinfo;

It can be opened again if needed, and the value of : cminrating in the SQL query associated with
the cursor would be the value of the host variable cminrating at that time.
Properties of Cursors : The general form of a cursor declaration is:
DECLARE cursomame [INSENSITIVE] [SCROLL] CURSOR
[WITH HOLD]
FOR some query
[ ORDER BY order-item-list ]
[ FOR READ ONLY I FOR UPDATE ]
A cursor can be declared to be a read-only cursor (FOR READ ONLY)

or, if it is a cursor on a base relation or an updatable view, to be an updatable cursor (FOR


UPDATE). If it is Updatable, simple variants of the UPDATE and DELETE commands allow us
to update or delete the row on which the cursor is positioned.

For example, if sinfo is an updatable cursor and open, execute the following statement:
UPDATE Sailors S
SET S.rating = S.rating ~ 1
WHERE CURRENT of sinfo;

This Embedded SQL statement modifies the rating value of the row currently pointed to by cursor
sinfo;
Dept. of CSE, HKBKCE Page 18
18CS53 Module 3 DBMS Notes

Similarly, delete this row by executing the next statement:


DELETE Sailors S
WHERE CURRENT of sinfo;
 A cursor is updatable by default unless it is a scrollable or insensitive cursor in which case
it is read-only by default.
 If the keyword SCROLL is specified, the cursor is scrollable, which means that variants of
the FETCH command can be used to position the cursor in very flexible ways; otherwise,
only the basic FETCH command, which retrieves the next row, is allowed.
 optional ORDER BY clause can be used to specify a sort order.

Dynamic SQL:-
 Consider an application such as a spreadsheet or a graphical front-end that needs to
access data from a DBMS.
 Such an application must accept commands from a user and, based on what the user needs,
generate appropriate SQL statements to retrieve the necessary data.
 SQL provides some facilities to deal with such situations; these are referred to as Dynamic
SQL.
 The two main commands, PREPARE and EXECUTE, through a simple example:

char c_sqlstring[] = {"DELETE FROM Sailors WHERE rating>5"};


EXEC SQL PREPARE readytogo FROM :csqlstring;
EXEC SQL EXECUTE readytogo;

 The first statement declares the C variable c_sqlstring and initializes its value to the string
representation of an SQL command.
 The second statement results in this string being parsed and compiled as an SQL command,
with the resulting executable bound to the SQL variable readytogo. (Since readytogo is an
SQL variable, just like a cursor name, it is not prefixed by a colon.)
 The third statement executes the command.

AN INTRODUCTION TO JDBC
Problems in embedded SQL DBMS-specific preprocessor transforms the Embedded SQL
statements into function calls in the host language. So even though the source code can be compiled
to work with different DBMSs, the final executable works only with one specific DBMS.

 ODBC and JDBC, short for Open DataBase Connectivity and Java DataBase
Connectivity, also enable the integration of SQL with a general-purpose programming
language.
 Both ODBC and JDBC expose database capabilities in a standardized way to the
application programmer through an application programming interface (API).
 In contrast to Embedded SQL, ODBC and JDBC allow a single executable to access
different DBMSs 'Without recompilation.
 Thus, while Embedded SQL is DBMS-independent only at the source code level,
applications using ODBC or JDBC are DBMS-independent at the source code level and
at the level of the executable.
 In addition, using ODBC or JDBC, an application can access not just one DBMS but
several different ones simultaneously.
 All direct interaction with a specific DBMS happens through a DBMS-specific driver.
 A driver is a software program that translates the ODBC or JDBC calls into DBMS-
specific calls.
Dept. of CSE, HKBKCE Page 19
18CS53 Module 3 DBMS Notes
 Drivers are loaded dynamically on demand since the DBMSs the application is going to
access are known only at run-time.
 Available drivers are registered with a driver manager
 The driver translates the SQL commands from the application into equivalent commands
that the DBMS understands
 An application that interacts with a data source through ODBC or JDBC selects a data
source, dynamically loads the corresponding driver, and establishes a connection with the
data source.
 There is no limit on the number of open connections, and an application can have several
open connections to different data sources.
 Each connection has transaction semantics; that is, changes from one connection are visible
to other connections only after the connection has committed its changes.
 While a connection is opcn, transactions are executed by submitting SQL statements,
retrieving results, processing errors, and finally committing or rolling back.
 The application disconnects from the data source to terminate the interaction.

Example for how to createJDBC Connection?


Steps to create JDBC connection:
 Register the database driver with java.sql.DriverManager, where DriverManager is a class
which is given under JDBC specifications. You can do this by loading driver
implementation class into the JVM by using Class.forName().
 Open a session to database, i.e. establish a connection to database. You can do this by
calling DriverManager.getConnection() method, which returns Connection object

package com.java2novice.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcConnection {
public static void main(String a[]){

try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager. getConnection("jdbc:oracle:thin:@<hostname>:<port
num>:<DB name>" ,"user","password");
Statement stmt = con.createStatement();
System.out.println("Created DB Connection....");
}

catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }

Dept. of CSE, HKBKCE Page 20


18CS53 Module 3 DBMS Notes

Architecture of JDBC
The architecture of JDBC has four main components:
1. The application,
2. Driver manager,
3. Specific drivers,
4. Data sources.

 The application initiates and terminates the connection with a data source. It sets
transaction boundaries, submits SQL statements, and retrieves the results all through a
well-defined interface as specified by the JDBC API.
 The primary goal of the driver manager is to load JDBC drivers and pass JDBC function
calls from the application to the correct driver.
 The data source processes commands from the driver and returns the results. Depending
on the relative location of the data source and the application, several architectural
scenarios are possible.

Drivers in JDBC are classified into four types depending on the architectural relationship between
the application and the data source:
1. Bridge: Translates SQL commands into non-native API.
Example: JDBC-ODBC bridge.
Code for ODBC and JDBC driver needs to be available on each client.
2. Direct translation to native API, non-Java driver:Translates SQL commands to native
API of data source.Need OS-specific binary on each client.
3. Network bridge:Send commands over the network to a middleware server that talks to the
data source. Needs only small JDBC driver at each client.
4. Direction translation to native API via Java driver: Converts JDBC calls directly to
network protocol used by DBMS. Needs DBMS-specific Java driver at each client

JDBC CLASSES AND INTERFACES

1. JDBC is a collection of Java classes and interfaces that enables database access from
programs written in the Java language.
2. It contains methods for connecting to a remote data source, executing SQL statements,
examining sets of results from SQL statements, transaction management, and exception
handling.
3. The classes and interfaces are part of the java. sql package.

Steps to submit a database query:


1. Load the JDBC driver
2. Connect to the data source
3. Execute SQL statements

Load the JDBC driver:-


 The first step in connecting to a data source is to load the corresponding JDBC driver. This
is accomplished by using the Java mechanism for dynamically loading classes.
 The following Java example code explicitly loads a JDBC driver:
Class.forName("oracle/jdbc.driver.OracleDriver");
 There are two other ways of registering a driver. We can include the driver When starting
the Java application:
- Djdbc.drivers=oracle/jdbc.driver at the command line

Dept. of CSE, HKBKCE Page 21


18CS53 Module 3 DBMS Notes
Connect to the data source:-
 A session with a data source is started through creation of a Connection object;
 A connection identifies a logical session with a data source; multiple connections within
the same Java program can refer to different data sources or the same data source.
 Connections are specified through a JDBC URL, a URL that uses the jdbc protocol.

Such a URL has the form


jdbc:<subprotocol>:<otherParameters>

In JDBC, connections can have different properties.


For example,
 A connection can specify the granularity of transactions. If auto commit is set for a
connection, then each SQL statement is considered to be its own transaction.
 When auto commit is off, then a series of statements that compose a transaction can be
committed using the commit() method of the Connection class, or aborted using the
rollback() method.
 The Connection class has methods to set the auto commit mode (Connection.
setAutoCommit) and to retrieve the current autocommit mode (getAutoCommit).

The following methods are part of the Connection interface and permit setting and getting
other properties:
 public int getTransactionIsolation() and void setTransactionIsolation(int level):-Sets
isolation level for the current connection.
 public boolean getReadOnly() and void setReadOnly(boolean b):-Specifies whether
transactions in this connection are readonly
 public boolean getAutoCommit() and Void setAutoCommit(boolean b):-If auto
commit is set, then each SQL statement is considered its own transaction. Otherwise, a
transaction is committed using commit(), or aborted using rollback().
 public boolean isClosed():-Checks whether connection is still open.

Establishing a connection to a data source is a costly operation since it involves several steps, such
as establishing a network connection to the data source, authentication, and allocation of
resources such as memory

Executing SQL Statements:-


JDBC supports three different ways of executing statements:
1. Statement
2. PreparedStatement
3. CallableStatement.

Statement class :The Statement class is the base class for the other two statement classes. It allows
us to query the data source with any static or dynamically generated SQL query

Prepared Statement class : The PreparedStatement class dynamically generates precompiled


SQL statements that can be used several times; these SQL statements can have parameters, but
their structure is fixed when the PreparedStatement object (representing the SQL statement) is
created.

Example:-
1. The SQL query specifies the query string, but uses ''1' for the values of the parameters,
which are set later using methods setString, setFloat, and setlnt.

Dept. of CSE, HKBKCE Page 22


18CS53 Module 3 DBMS Notes
2. The ''1' placeholders can be used anywhere in SQL statements where they can be replaced
with a value.
3. Examples of places where they can appear include the WHERE clause (e.g., 'WHERE
author=?'), or in SQL UPDATE and INSERT staternents, as in Figure 6.1.
4. The method setString is one way to set a parameter value; analogous methods are available
for int, float, and date.
5. It is good style to always use clearParameters()before setting parameter values in order to
remove any old data

/ / initial quantity is always zero


String sql = "INSERT INTO Books VALUES('?, 7, '?, ?, 0, 7)";
PreparedStatement pstmt = con.prepareStatement(sql);
/ / now instantiate the parameters with values
/ / assume that isbn, title, etc. are Java variables that contain the values to be inserted
pstmt.clearParameters() ;
pstmt.setString(l, isbn);
pstmt.setString(2, title);
pstmt.setString(3, author);
pstmt.setInt(4, qty);
pstmt.setFloat(5, price);
pstmt.setInt(6, year);
int numRows = pstmt.executeUpdate();

Figure 6.1 : SQL Update Using a Prepared Statement Object.

Note:-
1. The executeUpdate command, which is used if the SQL statement does not return any
records (SQL UPDATE, INSERT, ALTER, and DELETE statements).
2. The executeUpdate method returns an integer indicating the number of rows the SQL
statement modified; it returns 0 for successful execution without modifying any rows.

ExecuteQuery method:- The executeQuery method is used if the SQL statement returns data,
such as a regular SELECT query.

ResultSets:-(same as cursor in embedded SQL) : The statement executeQuery returns a,


ResultSet object, which is similar to a cursor
 The ResultSet object allows us to read one row of the output of the query at a time. Initially,
the ResultSet is positioned before the first row, and to retrieve the first row with an explicit
call to the next() method.
 The next method returns false if there are no more rows in the query answer, and true
otherwise.

Example:- ResultSet rs=stmt.executeQuery(sqlQuery);


/ / rs is now a cursor
/ / first call to rs.next()moves to the first record
/ / rs.next()moves to the next row
String sqlQuery=”select * from emp”;
ResultSet rs = stmt.executeQuery(sqlQuery)
while (rs.next()) {
/ / process the data
}
Figure 6.2 Using a ResultSet Object
Dept. of CSE, HKBKCE Page 23
18CS53 Module 3 DBMS Notes

 next ()- allows us to retrieve the logically next row in the query answer
 previous () -moves back one row.
 absolute (int num)- moves to the row with the specified number.
 relative (int num) -moves forward or backward (if num is negative) relative to the current
position. relative (-1) has the same effect as previous.
 first () -moves to the first row
 Last()- moves to the last row.

Example:- The following example shows how to access fields of the current ResultSet row using
accesssor methods.
ResultSet rs=stmt.executeQuery(sqIQuery);
String sqlQuerYi
ResultSet rs = stmt.executeQuery(sqIQuery)
while (rs.next() {
isbn = rs.getString(l);
title = rs.getString(" TITLE");
/ / process isbn and title
}

Or

How to execute and read select queries using jdbc?


This example shows how to read records from SQL select query. By using
Statement.executeQuery() you can execute select statements. JDBC ResultSet object provides
methods to read each column details on each row.

package com.java2novice.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MyResultSetEx {
public static void main(String a[]){
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager
.getConnection("jdbc:oracle:thin:@<hostname>:<port num>:<DB name>"
,"user","password");
Statement stmt = con.createStatement();
System.out.println("Created DB Connection....");
ResultSet rs = stmt.executeQuery("select name, salary from emp");
while(rs.next()){
System.out.println(rs.getString("name"));
System.out.println(rs.getInt("salary"));
}
rs.close();
con.close();
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
Dept. of CSE, HKBKCE Page 24
18CS53 Module 3 DBMS Notes
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

JDBC: Exceptions and Warnings


 Most of java.sql can throw and SQLException if an error occurs.
 SQLWarning is a subclass of SQLException;not as severe (they are not thrown and their
existence has to be explicitly tested)

Example
try {
stmt=con.createStatement();
warning=con.getWarnings();
while(warning != null) {
// handle SQLWarnings;
warning = warning.getNextWarning():
}
con.clearWarnings();
stmt.executeUpdate(queryString);
warning = con.getWarnings();

} //end try
catch( SQLException SQL e) {// handle the exception}

Examining Database Metadata : DatabaseMetaData object gives information about the database
system and the catalog.
Example:-
DatabaseMetaData md = con.getMetaData();
// print information about the driver:
System.out.println(“Name:” + md.getDriverName() + “version: ” + md.getDriverVersion());

SQLJ : SQLJ (SQL Java) was developed to complement the dynamic way of creating queries in
JDBC with a static model. It is therefore very close to Embedded SQL.
For example, in both SQLJ and Embedded
 SQL, variables in the host language always are bound statically to the same arguments,
 whereas in JDBC, need separate statements to bind each variable to an argument and to
retrieve the result.

For example, the following


SQLJ statement binds host language variables title, price, and author to the return values of the
cursor books.
#sql books = {
SELECT title, price INTO :title, :price
FROM Books WHERE author = :author
};
In JDBC, we can dynamically decide which host language variables will hold the query result.
In the following example,

Dept. of CSE, HKBKCE Page 25


18CS53 Module 3 DBMS Notes
Read the title of the book into variable ftitle if the book was written by Feynman, and into
variable otitle otherwise:
/ / assume have a ResultSet cursor rs
author = rs.getString(3);
if (author=="Feynman") {
ftitle = rs.getString(2):
}
else {
otitle = rs.getString(2);
}

 When writing SQLJ applications, write regular Java code and embed SQL statements
according to a set of rules.
 SQLJ applications are pre-processed through an SQLJ translation program that replaces
the embedded SQLJ code with calls to an SQLJ Java library.
 The modified program code can then be compiled by any Java compiler.
 Usually the SQLJ Java library makes calls to a JDBC driver, which handles the connection
to the database system.

Writing SQLJ Code


selects records from the Books table that match a given author.
String title; Float price; String author;
#sql iterator Books (String title, Float price);
Books books;
/ / the application sets the author
/ / execute the query and open the cursor
#sql books = {
SELECT title, price INTO :titIe, :price
FROM Books WHERE author = :author
};
/ / retrieve results
while (books.next()) {
System.out.println(books.titleO + ", " + books.price());
}
books.close() ;

JDBC code : The corresponding JDBC code fragment looks as follows (assuming we also
declared price, name, and author:

PrcparcdStatcment stmt = connection.prepareStatement(


" SELECT title, price FROM Books WHERE author = ?");
/ / set the parameter in the query and execute it
stmt.setString( 1, author);
ResultSet rs = stmt.executeQuery();
/ / retrieve the results
while (rs.next()) {
System.out.println(rs.getString(l) + ", " + rs.getFloat(2));
}

STORED PROCEDURES
 It is often important to execute some parts of the application logic directly in the process
space of the database system.
Dept. of CSE, HKBKCE Page 26
18CS53 Module 3 DBMS Notes
 Running application logic directly at the database has the advantage that the amount of data
that is transferred between the database server and the client issuing the SQL statement can
be minimized, while at the same time utilizing the full power of the database server.
 stored procedure is a program that is executed through a single SQL statement that can be
locally executed and completed within the process space of the database server.
 The results can be packaged into one big result and returned to the application, or the
application logic can be performed directly at the server, without having to transmit the
results to the client at all
 Once a stored procedure is registered with the database server, different users can re-use
the stored procedure, eliminating duplication of efforts in writing SQL queries or
application logic, and making code maintenance easy
 In addition, application programmers do not need to know the the databa.se schema if we
encapsulate all database access into stored procedures.

Creating a Simple Stored Procedure : Stored procedures without parameters:


CREATE PROCEDURE ShowNumReservations
SELECT S.sid, S.sname, COUNT(*)
FROM Sailors S, Reserves R
WHERE S.sid = R.sid
GROUP BY S.sid, S.sname

Stored procedures can have parameters: Three different modes: IN, OUT, INOUT

CREATE PROCEDURE IncreaseRating(


IN sailor_sid INTEGER, IN increase INTEGER)
UPDATE Sailors
SET rating = rating + increase
WHERE sid = sailor_sid

1. IN parameters are arguments to the stored procedure.


2. OUT parameters are returned from the stored procedure; it assigns values to all OUT
parameters that the user can process.
3. INOUT parameters combine the properties of IN and OUT parameters: They contain
values to be passed to the stored procedures, andthe stored procedure can set their values
as return values.

Calling Stored Procedures:- Stored procedures can be called in interactive SQL with the CALL
statement:
CALL storedProcedureName(argumentl, argument2, ... , argumentN);
Example:-
CALL IncreaseRating( IN sailor_sid INTEGER, IN increase INTEGER);

In Embedded SQL:-
EXEC SQL BEGIN DECLARE SECTION
char isbn[lO];
long qty;
EXEC SQL END DECLARE SECTION
/ / set isbn and qty to some values
EXEC SQL CALL AddInventory(:isbn,:qty);

In JDBC:-
CallableStatement cstmt=
Dept. of CSE, HKBKCE Page 27
18CS53 Module 3 DBMS Notes
con. prepareCall(" {CALL ShowNumberOfOrders}");
ResultSet rs = cstmt.executeQueryO
while (rs.next())

In SQLJ:-
/ create the cursor class
#sql !terator CustomerInfo(int cid, String cname, int count);
/ / create the cursor
CustomerInfo customerinfo;

/ / call the stored procedure


#sql customerinfo = {CALL ShowNumberOfOrders};
while (customerinfo.nextO) {
System.out.println(customerinfo.cid() + "," +
customerinfo.count()) ;
}

CASE STUDY: THE INTERNET BOOK SHOP:-


Recall that DBDudes settled on the following schema:
Books( isbn: CHAR(10), title: CHAR(8), author: CHAR(80), qty_in_stock: INTEGER,
price: REAL, year_published: INTEGER)
Customers( cid: INTEGER, cname: CHAR(80), address: CHAR(200))
Orders(ordernum: INTEGER, isbn: CHAR(lO), cid: INTEGER,cardnum: CHAR(l6),
qty: INTEGER, order_date: DATE, ship_date: DATE)

Tasks performed by customers include the following.


1. Customers search books by author name, title, or ISBN.
2. Customers register with the website.
3. Registered customers might want to change their contact information. DBDudes realize
that they have to augment the Customers table with additional information to capture login
and password information for each customer;
4. Customers check out a final shopping basket to complete a sale.
5. Customers add and delete books from a 'shopping basket' at the website.
6. Customers check the status of existing orders and look at old orders.

Administrative tasks performed by employees of B&N are listed next.


1. Employees look up customer contact information.
2. Employees add new books to the inventory.
3. Employees fulfill orders, and need to update the shipping date of individual books.
4. Employees analyze the data to find profitable customers and customers likely to respond
to special marketing campaigns.

Solution:-
1.Customers search books by author name, title, or ISBN
CREATE PROCEDURE SearchByISBN (IN book.isbn CHAR (10) )
SELECT B.title, B.author, B.qty_in_stock, B.price, B.year_published
FROM Books B
WHERE B.isbn = book.isbn

Individual books in the order are stored at the application layer in a Java array. To finalize
the order, they write the following JDBC code shown in below code which inserts the
elements from the array into the Orders table

Dept. of CSE, HKBKCE Page 28


18CS53 Module 3 DBMS Notes

String sql = "INSERT INTO Orders VALUES(7, 7, 7, 7, 7, 7)";


PreparedStatement pstmt = con.prepareStatement(sql);
con.setAutoCommit(false);
try {
/ / orderList is a vector of Order objects
/ / ordernum is the current order number
/ / dd is the ID of the customer, cardnum is the credit card number
for (int i=0; iiorderList.length(); i++)
/ / now instantiate the parameters with values
Order currentOrder = orderList[i];
pstmt.clearParameters() ;
pstmt.setInt(l, ordernum);
pstmt.setString(2, Order.getlsbn());
pstmt.setInt(3, dd);
pstmt.setString(4, creditCardNum);
pstmt.setlnt(5, Order.getQty());
pstmt.setDate(6, null);
pstmt.executeUpdate();
}
con.commit();
catch (SqLException e){
con.rollback();
System.out. println (e.getMessage());
}

Connection:- Establishing a connection to a database,


String uri = .. jdbc:oracle:www.bookstore.com:3083..
Connection connection;
try {
Connection connection =
DriverManager.getConnection(urI, userId,password);
}
catch(SQLException excpt) {
System.out.println(excpt.getMessage());
return;
}

Execution SQL statement:- Adding new books to the inventory


/ / initial quantity is always zero
String sql = "INSERT INTO Books VALUES('?, 7, '?, ?, 0, 7)";
PreparedStatement pstmt = con.prepareStatement(sql);
/ / now instantiate the parameters with values
/ / assume that isbn, title, etc. are Java variables that
/ / contain the values to be inserted

pstmt.clearParameters() ;
pstmt.setString(l, isbn);
pstmt.setString(2, title);
pstmt.setString(3, author);
pstmt.setFloat(5, price);
pstmt.setInt(6, year);

Dept. of CSE, HKBKCE Page 29


18CS53 Module 3 DBMS Notes
int numRows = pstmt.executeUpdate();

Processing results from SQL queries


ResultSet rs=stmt.executeQuery(sqlQuery);
/ / rs is now a cursor
/ / first call to rs.next() moves to the first record
/ / rs.next() moves to the next row
String sqlQuery;
ResultSet rs = stmt.executeQuery(sqlQuery)
while (rs.next()) {
/ / process the data
}

For each customer, showing how many orders he or she has placed. We showed a sample
stored procedure for this query
CREATE PROCEDURE ShowNumberOfOrders
SELECT C.cid, C.cname, COUNT(*)
FROM Customers C, Orders a
WHERE C.cid = O.cid
GROUP BY C.cid, C.cname

Increasing the available number of copies of a book by adding inventory,


CREATE PROCEDURE Addlnventory (
IN book_isbn CHAR(10),
IN addedQty INTEGER)
UPDATE Books
SET
WHERE
qty_in_stock = qtyjn_stock + addedQty
bookjsbn = isbn

Ranking customers according to their purchases


CREATE PROCEDURE RankCustomers(IN number INTEGER)
LANGUAGE Java
EXTERNAL NAME 'file:/ / /c:/storedProcedures/rank.jar'

DBDudcs takes care to make the application robust by processing exceptions


and warnings
try {
stmt = con.createStatement();
warning = con.getWarnings();
while( warning != null) {
/ / handleSQLWarnings / / code to process warning
warning = warning.getNextWarningO; / /get next warning
}
con.clear\Varnings() ;
stmt.executeUpdate( queryString );
warning = stmt.getWarnings();
while( warning != null) {
/ / handleSQLWarnings / / code to process warning
warning = warning.getNextWarning(); / /get next warning

Dept. of CSE, HKBKCE Page 30


18CS53 Module 3 DBMS Notes
}
} / / end try
catch ( SQLException SQLe) {
/ / code to handle exception
} / / end catch

Whenever a new order is entered into the Orders table, it is inserted with ship~date set to
NULL. The trigger processes each row in the order and calls the stored procedure
'UpdateShipDate'.
CREATE TRIGGER update_ShipDate
AFTER INSERT ON Orders // 1* Event *j
FOR EACH ROW
BEGIN CALL UpdatcShipDate(new); END //1* Action *j
INTERNET APPLICATIONS:

THE THREE-TIER APPLICATION ARCHITECTURE


In this section, we discuss the overall architecture of data-intensive Internet applications. Data-
intensive Internet applications can be understood in terms of three different functional
components: data management, application logic, and presentation. The component that
handles data management usually utilizes a DBMS for data storage, but application logic and
presentation involve much more than just the DBMS itself.

Single-Tier
In this section, we provide some perspective on the three-tier architecture by discussing single-
tier and client-server architectures, the predecessors of the three-tier architecture. Initially, data-
intensive applications were combined into a single tier, including the DBMS, application logic,
and user interface, as illustrated in Figure 7.5. The application typically ran on a mainframe, and
users accessed it through dumb terminals that could perform only data input and display. This
approach has the benefit of being easily maintained by a central administrator.

The Three Layers

Single-tier architectures have an important drawback: Users expect graphical interfaces that
require much more computational power than simple dumb terminals. Centralized computation of
the graphical displays of such interfaces requires much more computational power than a single
server has available, and thus single-tier architectures do not scale to thousands of users.

Dept. of CSE, HKBKCE Page 31


18CS53 Module 3 DBMS Notes
Presentation tier
Primary interface to the user
Needs to adapt to different display devices (PC, PDA, cell phone, voice access?)

Middle tier
Implements business logic (implements complex actions, maintains state between different steps
of a workflow)
Accesses different data management systems

Data management tier


One or more standard database management systems

Example 1: Airline reservations


Build a system for making airline reservations

Database System : Airline info, available seats, customer info, etc.


Application Server : Logic to make reservations, cancel reservations, add new airlines, etc.
Client Program : Log in different users, display forms and human readable output

Example 2: Course Enrollment


Build a system using which students can enroll in courses
 Database System : Student info, course info, instructor info, course availability, pre-
requisites, etc.
 Application Server : Logic to add a course, drop a course, create a new course, etc.
 Client Program : Log in different users (students, staff, faculty), display forms and human-
readable output

Two Tier or Client-Server Architectures


 The commoditization of the PC and the availability of cheap client computers led to the
development of the two-tier architecture.
 Two-tier architectures, often also referred to as client-server architectures, consist of a
client computer and a server computer, which interact through a well-defined protocol.
What part of the functionality the client implements, and what part is left to the server, can
vary.
 In the traditional client server architecture, the client implements just the graphical user
interface, and the server. Implements both the business logic and the data management;
such clients are often called thin clients, and this architecture.

 Other divisions are possible, such as more powerful clients that implement both user
interface and business logic, or clients that implement user interface and part of the
business logic, with the remaining part being implemented at the server level; such clients
are often called thick clients, and this architecture is illustrated as

Dept. of CSE, HKBKCE Page 32


18CS53 Module 3 DBMS Notes

The thick-client model has several disadvantages when compared to the thinclient model. First,
there is no central place to update and maintain the business logic, since the application code runs
at many client sites. Second, a large amount of trust is required between the server and the clients.A
third disadvantage of the thick-client architecture is that it does not scale with the number of
clients; it typically cannot handle more than a few hundred clients.

Three Tier Architectures : The thin-client two-tier architecture essentially separates presentation
issues from the rest of the application. The three-tier architecture goes one step further, and also
separates application logic from data management:

Overview of the Presentation Tier


 At the presentation layer, need to provide forms through which the user can issue requests,
and display responses that the middle tier generates.
 The hypertext markup language (HTML) is the basic data presentation language.
 It is important that this layer of code be easy to adapt to different display devices and
formats; for example, regular desktops versus handheld devices versus cell phones.
 This adaptivity can be achieved either at the middle tier through generation of different
pages for different types of client, or directly at the client through style sheets that specify
how the data should be presented.
 In the latter case, the middle tier is responsible for producing the appropriate data in
response to user requests, whereas the presentation layer decides how to display that
information.

Overview of the Middle Tier


 The middle layer runs code that implements the business logic of the application:
 It controls what data needs to be input before an action can be executed, determines the
control flow between multi-action steps, controls access to the database layer, and often
assembles dynamically generated HTML pages from database query results.
 The middle tier code is responsible for supporting all the different roles involved in the
application.

For example,
In an Internet shopping site implementation,
 customers to be able to browse the catalog and make purchases, administrators to be able
to inspect current inventory, and possibly data analysts to ask summary queries about
purchase histories. Each of these roles can require support for several complex actions.

For example, consider the a customer who wants to buy an item (after browsing or searching the
site to find it).
Dept. of CSE, HKBKCE Page 33
18CS53 Module 3 DBMS Notes
 Before a sale can happen, the customer has to go through a series of steps:
 She has to add items to her shopping ba.sket,
 she has to provide her shipping address and credit card number (unless she has an account
at the site),
 she has to finally confirm the sale with tax and shipping costs added.
 Controlling the flow among these steps and remembering already executed steps is done at
the middle tier of the application.
 The data carried along during this series of steps might involve database accesses, but
usually it is not yet permanent (for example, a shopping basket is not stored in the database
until the sale is confirmed).

Advantages of the Three-Tier Architecture


 Heterogeneous systems : Tiers can be independently maintained, modified, and replaced
 Thin clients : Only presentation layer at clients (web browsers)
 Integrated data access : Several database systems can be handled transparently at the
middle tier Central management of connections
 Scalability : Replication at middle tier permits scalability of business logic. Code for
business logic is centralized and interaction between tiers through well-defined APIs: Can
reuse standard components at each tier

The Presentation Layer: Technologies for the client side of the three-tier architecture
1. HTML forms - as a special means of passing arguments from the client to the middle tier
2. JavaScript - a Java-based scripting language that can be used for light-weight computation
in the client tier (e.g., for simple animations).
3. Style sheets are languages that allow us to present the same webpage with different
formatting for clients with different presentation capabilities;

HTML Forms:
• HTML forms are a common way of communicating data from the client tier to the middle
tier
• The general format of a form is the following:
<FORM ACTION="page.jsp" METHOD="GET" NAME="LoginForm">

• ACTION: Specifies the URI of the page to which the form contents are submitted; if the
ACTION attribute is absent, then the URI of the current page is used
• METHOD: The HTTP/1.0 method used to submit the user input from the filled-out form
to the webserver. There are two choices, GET and POST
• NAME: This attribute gives the form a name
Dept. of CSE, HKBKCE Page 34
18CS53 Module 3 DBMS Notes

JavaScript: JavaScript is often used for the following types of computation at the client:
 Browser Detection: JavaScript can be used to detect the browser type and load a browser-
specific page.
 Form Validation: JavaScript is used to perform simple consistency checks on form fields.
For example, a JavaScript program might check whether aform input that asks for an email
address contains the character '@,' or if all required fields have been input by the user.
 Browser Control: This includes opening pages in customized windows; examples include
the annoying pop-up advertisements that you see at many websites, which are programmed
using JavaScript.
<SCRIPT LANGUAGE=" JavaScript" SRC="validateForm.js"> </SCRIPT>
<SCRIPT LANGUAGE=" JavaScript">
<\-
alert(" Welcome to our bookstore");
//-->
</SCRIPT>

Style Sheets:
• A style sheet is a method to adapt the same document contents to different presentation
formats.
• A style sheet contains instructions that tell a ‘web browser (or whatever the client uses to
display the webpage) how to translate the data of a document into a presentation that is
suitable for the client's display.

 There are two style sheet languages: XSL and CSS.


 CSS was created for HTML with the goal of separating the display characteristics of
different formatting tags from the tags themselves. The target files for CSS are HTML files
 XSL is an extension of ess to arbitrary XML docurnents; besides allowing us to define
ways of formatting objects, XSL contains a transformation language that enables us to
rearrange objects.The target files for XSL are XML files.

Cascading Style Sheets:


• A Cascading Style Sheet (CSS) defines how to display HTML elements
• Styles are normally stored in style sheets, which are files that contain style definitions
• It is included into an HTML file with the following line:
<LINK REL="style sheet" TYPE="text/css" HREF="books.css" />
 The selector is the element or tag whose format we are defining.

 The property indicates the tag's attribute whose value we want to set in the style sheet, and
the property is the actual value of the attribute.

XSL: XSL is a language for expressing style sheets

Dept. of CSE, HKBKCE Page 35


18CS53 Module 3 DBMS Notes
 An XSL style sheet is, like CSS, a file that describes how to display an XML document of
a given type. XSL shares the functionality of CSS and is compatible with it (although it
uses a different syntax).
• The capabilities of XSL vastly exceed the functionality of CSS.
• XSL contains the XSL Transformation language, or XSLT, a language that allows 11S to
transform the input XML document into a XML document with another structure.

THE MIDDLE TIER


• Technologies for the middle tier
– Common Gateway Interface, a protocol that is used to transmit arguments from
HTML forms to application programs running at the middle tier
– application servers - technologies for writing application logic at the middle tier
– Java servlets and Java Server Pages :Another important functionality is the
maintenance of state in the middle tier component of the application as the client
component goes through a series of steps to complete a transaction.

CGI: The Common Gateway Interface


• The Common Gateway Interface connects HTML forms with application programs. It is a
protocol that defines how arguments from forms are passed to programs at the server side.

Application Servers: An application server maintains a pool of threads or processes and uses these to
execute requests. Thus, it avoids the startup cost of creating a new process for each request.

• The client (a Web browser) interacts with the webserver through the HTTP protocol.
• The webserver delivers static HTML or XML pages directly to the client.
• To assemble dynamic pages, the webserver sends a request to the application server.
• The application server contacts one or more data sources to retrieve necessary data or sends
update requests to the data sources.

Dept. of CSE, HKBKCE Page 36


18CS53 Module 3 DBMS Notes
• After the interaction with the data sources is completed, the application server assembles
the webpage and reports the result to the webserver, which retrieves the page and delivers
it to the client.

Servlets:
• Java servlets are pieces of Java code that run on the middle tier, in either webservers or
application servers
• All servlets must implement the Servlet interface. In most cases, servlets extend the specific
HttpServlet class for servers that communicate with clients via HTTP.
• The HttpServlet class provides methods such as doGet and doPost to receive arguments
from HTML forms, and it sends its output back to the elient via HTTP

JavaServer Pages:
• JavaServer pages (.JSPs) interchange the roles of output and application logic.
• JavaServer pages are written in HTML with servlet-like code embedded in special HTML
tags.
• They are usually compiled into a servlet, which is then handled by a servlet container
analogous to other servlets.

Dept. of CSE, HKBKCE Page 37

You might also like