DBMS - Module 3
DBMS - Module 3
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.
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.
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.
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;
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.
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).
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.
IN comparison operators can always be expressed as a single block query. For example, Q3 may
be written as in Q4A:
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.
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.
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.
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.
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:
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
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:
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’;
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;
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).
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.
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`.
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;
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;
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.
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 ) );
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.
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.
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:
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’;
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.
For example, to remove the COMPANY database schema and all its tables, domains, and other
elements, the CASCADE option is used as follows:
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:
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.
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,
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.
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.
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;
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);
Or
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 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:
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)
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
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:
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.
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();
}
} }
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
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.
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
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
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.
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.
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
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();
}
}
}
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.
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.
JDBC code : The corresponding JDBC code fragment looks as follows (assuming we also
declared price, name, and author:
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.
Stored procedures can have parameters: Three different modes: IN, OUT, INOUT
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;
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
pstmt.clearParameters() ;
pstmt.setString(l, isbn);
pstmt.setString(2, title);
pstmt.setString(3, author);
pstmt.setFloat(5, price);
pstmt.setInt(6, year);
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
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:
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.
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.
Middle tier
Implements business logic (implements complex actions, maintains state between different steps
of a workflow)
Accesses different data management systems
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
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:
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).
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.
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.
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.
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.