0% found this document useful (0 votes)
7 views

Module 3 Part 2

Uploaded by

Ratan Shet
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)
7 views

Module 3 Part 2

Uploaded by

Ratan Shet
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/ 19

MODULE –III NOTES DBMS -15CS53 V sem CSE/ISE

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, delete, and
modify data. SQL queries canbe used to retrieve desired data. but we need to bridge an important
differencein how a database system sees data and how an application program in alanguage like Java or C
sees data: The result of a database query is a set (ormultiset) or records, hut Java has no set or multiset
data type. This mismatchis resolved through additional SQL constructs that allow applications to obtain
a handle on a collection and iterate over the records one at a time.

6.1 ACCESSING DATABASES FROM APPLICATIONS


In this section, we cover how SQL commands can be executed from within aprogram in a host language
such as C or Java. The use of SQL commandswithin a host language program is called Embedded SQL.
Details of Embedded SQL also depend on the host language. Although similar capabilities are
supported for a variety of host languages, the syntax sometimes varies.

6.1.1 Embedded SQL


Conceptually, embedding SQL commands in a host language program is straightforward.SQL
statements (i.e., not declarations) can be used wherever a statementin the host language is allowed (with a
few restrictions). SQL statementsmust be clearly marked so that a preprocessor can deal with them before
invokingthe compiler for the host language. Also, any host language variablesused to pass arguments into
an SQL command must be declared in SQL. Inparticular, some special host language variables must be
declared in SQL (sothat, for example, any error conditions arising during SQL execution can
becommunicated back to the main application program in the host language).

There are, however, two complications to bear in mind. First, the data typesrecognized by SQL
may not be recognized by the host language and vice versa.This mismatch is typically addressed by
casting data values appropriately beforepassing them to or frorn SQL commands.The second
complication hasto do with SQL being set-oriented,and is addressed using cursors.

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:
EXEC SQL BEGIN DECLARE SECTION
charc_sname[20];
longcsid;
short crating;
float cage;
EXEC SQL END DECLARE SECTION
The SQL-92 standard defines a correspondence between the host language types and SQL types
for a number of host languages. In our example, c_snamc has the type CHARACTER(20) when referred

Gururaj.T , Asso.Professor, Dept of CSE,SJMIT . Page 1


MODULE –III NOTES DBMS -15CS53 V sem CSE/ISE
to in an SQL statement, csid has the type INTEGER, crating has the type SMALLINT, and cage has the
type REAL.
The SQL-92 standard recognizes two special variables for reporting errors, SQLCODE and
SQLSTATE.

Embedding SQL Statements


All SQL staternents embedded within a host program must be clearly marked, with the details
dependent on the host language; in C, SQL statements must be prefixed by EXEC SQL.
As a simple example, the following EmbeddedSQL statement inserts a row, whose column values
are 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);
The SQLSTATE variable should be checked for errors and exceptions after each Embedded SQL
statement. SQL provides the WHENEVER command to simplify this tedious task:
EXEC SQL WHENEVER [SQLERROR IF NOT FOUND] [ CONTINUE I GOTO stmt ]
The intent is that the value of SQLSTATE should bechecked after each Embedded SQL statement is
executed. 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 NO
DATA.

6.1.2 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.
We can declare a cursor on any relation or on any SQL query (because every query returns a set
of rows). Once a cursor is declared, we can 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.

Basic Cursor Definition and Usage


cursors enable us to examine, in the host language program, a collection of rows computed by an
Embedded SQL statement:
We usually need to open a cursor if the embedded statement is a SELECT query. However, we
can avoid opening a cursor if the answer contains a single row.
INSERT, DELETE, and UPDATE statements typically require no cursor, although some variants
of DELETE and UPDATE use a cursor.
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
SELECTS.sname, S.age
INTO :c_sname, :c_age
FROM Sailors S WHERES.sid = :c_sid;
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.

Gururaj.T , Asso.Professor, Dept of CSE,SJMIT . Page 2


MODULE –III NOTES DBMS -15CS53 V sem CSE/ISE
But what about the following query, which computes the names and ages of all sailors with a
rating greater than the current value of the host variable c_minrating?
SELECT S.sname, S.age
FROM Sailors S
WHERE S.rating> :c_minrating

A cursor can be thought of as 'pointing' to a row in the collection of answers to the query
associated with it. When a cursor is opened, it is positioned just before the first row. We can use the
FETCH command to read the first row of cursor sinfo into host language variables:
FETCH sinfoINTO :c_sname, :c_age;
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), we can read all the rows computed by the
query, one row at a time. Additional parameters to the FETCH command allow us to position a cursor in
very flexible ways.
How do we know when we have looked at all the rows associated with the cursor? By looking at
the special variables SQLCODE or SQLSTATE, of course. SQLSTATE, for example, is set to the value
02000, which denotes NO DATA, to indicate that there are no more rows ifthe FETCH statement
positions the cursor after the last row.
When we are done with a cursor, we can close it:
CLOSE sinfo;
It can be opened again if neededand the value of :c_minrating in the SQL query associated with
the cursor would be the value of the host variable c_minrating at that time.

Gururaj.T , Asso.Professor, Dept of CSE,SJMIT . Page 3


MODULE –III NOTES DBMS -15CS53 V sem CSE/ISE

DELETE commands allow us to update or delete the row on which the cursor is positioned.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;If the keyword INSENSITIVE is specified, the cursor
behaves as if it is ranging over a private copy of the collection of answer rows.A holdable cursor is
specified using the WITH HOLD clause, and is not closed when the transaction is conunitted.Finally, in
what order do FETCH commands retrieve rows? In general this order is unspecified, but the optional
ORDER BY clause can be used to specify a sort order. Note that columns mentioned in the ORDER BY
clause cannot be updated through the cursor!

6.1.3 Dynamic SQL

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.

Gururaj.T , Asso.Professor, Dept of CSE,SJMIT . Page 4


MODULE –III NOTES DBMS -15CS53 V sem CSE/ISE
6.2 AN INTRODUCTION TO JDBC
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).
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.

6.2.1JDBC Architecture
The architecture of JDBC has four main components: the application, the driver manager,
several data source specific drivers, and the corresponding 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 driver establishes the connection with the data source.
The data source processes commands from the driver and returns the results.

Driversin JDBC are classified into four types depending on the architectural relationship between the
application and the data source:

Gururaj.T , Asso.Professor, Dept of CSE,SJMIT . Page 5


MODULE –III NOTES DBMS -15CS53 V sem CSE/ISE

6.3 JDBC CLASSES AND INTERFACES

JDBC is a collection of Java classes and interfaces that enables database access from programs
written in the Java language. 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. The classes and interfaces are part of the java.sql package. Thus, all code fragments in the
remainder of this section should include the statement import java. sql .* at the beginning of the code;

6.3.1 JDBC Driver Management


In JDBC, data source drivers are managed by the Drivermanager class, which maintains a list of
all currently loaded drivers. The Drivermanager class hasmethods registerDriver, deregisterDriver, and
getDrivers to enable dynamic addition and deletion of drivers.
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 static method forName
in the Class class returns the Java class as specified in the argument string and executes its static
constructor. The static constructor of the dynamically loaded class loads an instance of the Driver class,
and this Driver object registers itself with the DriverManager class.
The following Java example code explicitly loads a JDBC driver:
Class.forName("oracle/jdbc.driver.OracleDriver");

6.3.2 Connections
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>
The code example shown in Figure 6.2 establishes a connection to an Oracle database assuming that the
strings userld and password are set to valid values.

Gururaj.T , Asso.Professor, Dept of CSE,SJMIT . Page 6


MODULE –III NOTES DBMS -15CS53 V sem CSE/ISE

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. In case an application establishes many different connections from different parties (such as a
Web server), connections are often pooled to avoid this overhead. A connection pool is a set of
established connections to a data source. Whenever a new connection is needed, one of the connections
from the pool is used, instead of creating a new connection to the data source.

6.3.3 Executing SQL Statements


We now discuss how to create and execute SQL statements using JDBC. In the JDBC code examples in
this section, we assume that we have a Connection object named con. JDBC supports three different ways
ofexecuting statements: Statement, PreparedStatement, and CallableStatement. The Statement class is the
base class for the other two statment classes. It allows us to query the data source with any static or
dynamically generated SQL query.
The PreparedStatement class is 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.
Consider the sample code using a PreparedStatment object shown in Figure 6.3. The SQL query
specifies the query string, but uses ''?' for the values of the parameters, which are set later using methods
setString,setFloat, and setlnt. The ''?' placeholders can be used anywhere in SQL statements where they
can be replaced with a value. 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.3.
The method setString is one wayto set a parameter value; analogous methods are available for int,
float, and date. It is good style to always use clearParameters() before setting parameter values in order to
remove any old data.

Gururaj.T , Asso.Professor, Dept of CSE,SJMIT . Page 7


MODULE –III NOTES DBMS -15CS53 V sem CSE/ISE

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.
The executeQuery method is used if the SQL statement returns data, such &"l in a regular
SELECT query.JDBC has its own cursor mechanism in the form of a ResultSet object, which we discuss
next. The execute method is more general than executeQuery and executeUpdate.

6.3.4 ResultSets
The statement executeQuery returns a, ResultSet object, which is similar to a cursor. ResultSet
cursors in JDBC 2.0 are very powerful; they allow forward and reverse scrolling and in-place editing and
insertions.
In its most basic form, 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 we have to retrieve the first row with
an explicit call to the next0 method. The next method returns false if there are no more rows in the query
answer, and true other\vise. The code fragment shown in Figure 6.4 illustrates the basic usage of a
ResultSet object.

Gururaj.T , Asso.Professor, Dept of CSE,SJMIT . Page 8


MODULE –III NOTES DBMS -15CS53 V sem CSE/ISE
Matching Java and SQL Data Types
JDBC provides special data types and specifies their relationship to corresponding SQL data
types. Figure 6.5 shows the accessor methods in a ResultSet object for the most common SQL datatypes.
With these accessor methods, we can retrieve values from the current row of the query result referenced
by the ResultSet object. There are two forms for each accessor method: One method retrieves values by
column index, starting at one, and the other retrieves values by column name. The following example
shows how to access fields of the current ResultSet row using accesssor methods.

6.3.5 Exceptions and Warnings


Similar to the SQLSTATE variable, most of the methods in java.sql can throw an exception of the type
SQLException if an error occurs. The information includes SQLState, a string that describes the error
(e.g., whether the statement contained an SQL syntax error). In addition to the standard getMessage0
method inherited from Throwable, SQLException has two additional methods that provide further
information, and a method to get (or chain) additional exceptions:

An SQL Warning is a subclass of SQLException. Warnings are not severe as errors and the program can
usually proceed without special handling of warnings. Warnings are not thrown like other exceptions, and

Gururaj.T , Asso.Professor, Dept of CSE,SJMIT . Page 9


MODULE –III NOTES DBMS -15CS53 V sem CSE/ISE
they are not caught as part of the try"-catch block around a java.sql statement. We Heed to specifically
test whether warnings exist. Connection, Statement, and ResultSet objects all have a getWarnings 0
method with which we can retrieve SQL warnings if they exist. Statement objects clear warnings
automatically on execution of the next statement; ResultSet objects clear warnings every time a new tuple
is accessed.

6.3.6 Examining Database Metadata


we can use theDatabaseMetaData object to obtain information about the database system itself, as well as
information from the database catalog. For example, the following code fragment shows how to obtain
the name and driver version of the JDBC driver:
DatabaseMetaData md = con.getMetaD<Lta():
System.out.println("Driver Information:");
System.out.println("Name:" + md.getDriverNameO + "; version:" + mcl.getDriverVersion());
The DatabaseMetaData object has many more methods.we list some methods here:
1) publicResultSet getCatalogs0 throws SqLException. This function returns a ResultSet that can be used
to iterate over all the catalog relations. The functions getIndexInfo0 and getTables0 work analogously.

Gururaj.T , Asso.Professor, Dept of CSE,SJMIT . Page 10


MODULE –III NOTES DBMS -15CS53 V sem CSE/ISE
2) publicintgetMaxConnections0 throws SqLException. This function returns the ma.ximum number of
connections possible.

We will conclude our discussion of JDBC with an example code fragment that examines all database
metadata shown in Figure 6.7.

6.4 SQLJ
SQLJ (short for 'SQL-Java') was developed by the SQLJ Group, a group of database vendors and
Sun. SQLJ was developed to complement the dynamic way of creating queries in JDBC with a static
model. It is therefore very close to Embedded SQL. Unlike JDBC, having semi-static SQL queries allows
the compiler to perform SQL syntax checks, strong type checks of the compatibility of the host variables
with the respective SQL attributes, and consistency of the query with the database schema-tables,
attributes, views, and stored procedures--all at compilation time. For example, in both SQLJ and
Embedded SQL, variables in the host language always are bound statically to the same arguments,
whereas in JDBC, we need separate statements to bind each variable to an argument and to retrieve the

Gururaj.T , Asso.Professor, Dept of CSE,SJMIT . Page 11


MODULE –III NOTES DBMS -15CS53 V sem CSE/ISE
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, we read the title of the book into variable ftitle if the book was written by Feynman,
and into variable otitle otherwise:
/ / assume we 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, we just 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.

6.4.1 Writing SQLJ Code


We will introduce SQLJ by means of examples. Let us start with an SQLJ code fragment that selects
records from the Books table that match a given author.

Gururaj.T , Asso.Professor, Dept of CSE,SJMIT . Page 12


MODULE –III NOTES DBMS -15CS53 V sem CSE/ISE
The corresponding JDBC code fragment looks as follows (assuming we also declared price, name, and
author:

System.out.println(rs.getString(l) + ", " + rs.getFloat(2));


}

Comparing the JDBC and SQLJ code, we see that the SQLJ code is much easier to read than the JDBC
code. Thus, SQLJ reduces software development and maintenance costs.

Let us consider the individual components of the SQLJ code in more detail. All SQLJ statements
have the special prefix #sql. In SQLJ, we retrieve the results of SQL queries with iterator objects, which
are basically cursors. An iterator is an instance of an iterator class. Usage of an iterator in SQLJ goes
through five steps:

There are two types of iterator classes: named iterators and positional iterators. For named iterators, we
specify both the variable type and the name of each column of the iterator. This allows us to retrieve
individual columns by name as in our previous example where we could retrieve the title colunm from the
Books table using the expression books.titIe(). For positional iterators, we need to specifY only the
variable type for each column of the iterator. To access the individual columns of the iterator, we use a
FETCH ... INTO construct, similar to Embedded SQL. Both iterator types have the same performance;
which iterator to use depends on the programmer's taste.

Gururaj.T , Asso.Professor, Dept of CSE,SJMIT . Page 13


MODULE –III NOTES DBMS -15CS53 V sem CSE/ISE
6.5 STORED PROCEDURES
It is often important to execute some parts of the application logic directly in the process space of
the database system. 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 databa.se server.
When SQL statements are issued from a remote application, the records in the result of the query
need to be transferred from the database system back to the application. If we use a cursor to remotely
access the results of an SQL statement, the DBMS has resources such as locks and memory tied up while
the application is processing the records retrieved through the cursor.
In contrast, a 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 ea."lY. In addition, application programmers do not need to know the the
databa.se schema if we encapsulate all databa.'3e access into stored procedures.
Although theyare called stored procedur'es, they do not have to be procedures in a programming
language sense; they can be functions.

6.5.1 Creating a Simple Stored Procedure


Let us look at the example stored procedure written in SQL shown in Figure (i.S. vVe see that stored
procedures must have a name; this stored procedurehas the name 'ShowNumberOfOrders.' Otherwise, it
just contains an SQL statement that is precompiled and stored at the server.

Let us look at an example of a stored procedure with arguments. The stored procedure shown in Figure
6.9 has two arguments: book_isbn and addedQty. It updates the available number of copies of a book with
the quantity from a new shipment.

Gururaj.T , Asso.Professor, Dept of CSE,SJMIT . Page 14


MODULE –III NOTES DBMS -15CS53 V sem CSE/ISE

Stored procedures do not have to be written in SQL; they can be written in any host language. As an
example, the stored procedure shown in Figure 6.10 is a Java function that is dynamically executed by the
database server whenever it is called by the client:

CREATE PROCEDURE RallkCustomers(IN number INTEGER)


LANGUAGE Java
EXTERNAL NAME 'file:// /c:/storedProcedures/rank.jar'

Figure 6.10 A Stored Procedure in Java

6.5.2 Calling Stored Procedures


Stored procedures can be called in interactive SQL with the CALL statement:

CALL storedProcedureName(argumentl, argument2, ... , argumentN);

Calling Stored Procedures from JDBC

Gururaj.T , Asso.Professor, Dept of CSE,SJMIT . Page 15


MODULE –III NOTES DBMS -15CS53 V sem CSE/ISE
Calling Stored Procedures from SQLJ

6.5.3 SQL/PSM
All major database systems provide ways for users to write stored procedures in a simple, general
purpose language closely aligned with SQL. In this section, we briefly discuss the SQL/PSM standard,
which is representative of most vendorspecific languages. In PSM, we define modules, which are
collections of stored procedures, temporary relations, and other declarations.

Each parameter is a triple consisting of the mode (IN, OUT, or INOUT as discussed in the previous
section), the parameter name, and the SQL datatype of the parameter.

We start out with an example of a SQL/PSM function that illustrates the main SQL/PSM
constructs. The function takes as input a customer identified by her cid and a year. The function returns
the rating of the customer, which is defined a...'3 follows: Customers who have bought more than ten
books during the year are rated 'two'; customer who have purchased between 5 and 10 books are rated
'one', otherwise the customer is rated 'zero'. The following SQL/PSM code computes the rating for a given
customer and year.

Gururaj.T , Asso.Professor, Dept of CSE,SJMIT . Page 16


MODULE –III NOTES DBMS -15CS53 V sem CSE/ISE
CREATE PROCEDURE RateCustomer(IN custId INTEGER, IN year INTEGER)
RETURNS INTEGER
DECLARE rating INTEGER;
DECLARE numOrders INTEGER;
SET numOrders = (SELECT COUNT(*) FROM Orders 0 WHERE O.tid = custId);
IF (numOrders>10) THEN rating=2;
ELSEIF (numOrders>5) THEN rating=1;
ELSE rating=O;
END IF;
RETURN rating;

Let us use this example to give a short overview of some SQL/PSM constructs:

6.6 CASE STUDY: THE INTERNET BOOK SHOP


DBDudes finished logical database design, as discussed in Section 3.8, and now consider the
queries that they have to support. They expect that the application logic will be implemented in Java, and
so they consider JDBC and SQLJ as possible candidates for interfacing the database system with
application code.
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)

Gururaj.T , Asso.Professor, Dept of CSE,SJMIT . Page 17


MODULE –III NOTES DBMS -15CS53 V sem CSE/ISE

CREATE PROCEDURE SearchByISBN (IN book.isbn CHAR (10) )


SELECT B.title, B.author, B.qty_in_stock,B.price, B.yeaLpublished
FROM Books B
WHERE B.isbn = book.isbn
Placing an order involves inserting one or more records into the Orders table.Since DBDudes has not yet
chosen the Java-based technology to program the application logic, they assume for now that the
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 Figure 6.11, which inserts the elements from the array into the
Orders table. Note that this code fragment assumes several Java variables have been set beforehand.

Gururaj.T , Asso.Professor, Dept of CSE,SJMIT . Page 18


MODULE –III NOTES DBMS -15CS53 V sem CSE/ISE

DBDudes writes other JDBC code and stored procedures for all of the remaining tasks. They use code
similar to some of the fragments that we have seen in this chapter.

DBDudcs takes care to make the application robust by processing exceptions and warnings, as
shown in Figure 6.6.
DBDudes also decide to write a trigger, which is shown in Figure 6.12. 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'. This stored procedure (whose code is not
shown here) updates the (anticipated) ship_date of the new order to 'tomorrow', in case qtyjlLstock of the
corresponding book in the Books table is greater than zero. Otherwise, the stored procedme sets the
ship_date to two weeks.

Gururaj.T , Asso.Professor, Dept of CSE,SJMIT . Page 19

You might also like