DBMS - Module 3 Ppts - Jan28th (Autosaved)
DBMS - Module 3 Ppts - Jan28th (Autosaved)
DBMS - Module 3 Ppts - Jan28th (Autosaved)
DATABASE APPLICATION
DEVELOPMENT
SQL : ADVANCE QUERIES
Constraints as Assertions
General constraints: constraints that do not fit in
the basic SQL categories
Mechanism: CREATE ASSERTION
components include: a constraint name, followed by
CHECK, followed by a condition
Assertions: An Example
“The salary of an employee must not be greater
than the salary of the manager of the department
that the employee works for’’
CREATE ASSERTION SALARY_CONSTRAINT
CHECK (NOT EXISTS (SELECT *
FROM EMPLOYEE E, EMPLOYEE M, DEPARTMENT D
WHERE E.SALARY > M.SALARY AND
E.DNO=D.NUMBER AND D.MGRSSN=M.SSN))
Using General Assertions
Specify a query that violates the condition; include
inside a NOT EXISTS clause
Query result must be empty
if the query result is not empty, the assertion has been
violated
SQL Triggers
Objective: to monitor a database and take action
when a condition occurs
Triggers are expressed in a syntax similar to
assertions and include the following:
event (e.g., an update operation)
condition
action (to be taken when the condition is satisfied)
SQL Triggers: An Example
A trigger to compare an employee’s salary to his/her
supervisor during insert or update operations:
compiler compiles the SQL code much before C compiles the code
for execution. Hence embedded SQLs will be faster in execution.
But in the case of dynamic SQL, queries are created, compiled and
executed only at the run time. This makes the dynamic SQL little
complex, and time consuming.
Cursor is a Temporary Memory or Temporary Work Station. It is
allocated by Database Server at the Time of Performing
cloud platform.
Any operations or data to perform in cloud this wil be
use.
Mongo DB:
Open source database which stores and index the data
in the form of collection of documents .
It produces high performance and it retrives data very
faster because of indexing than conventional db’s.
Introduction to JDBC
It is a standarad Java Application program interface quietly
used for database independent connection b/w Java
programming language and wide range of database with the
help of java API.
We can make a connection with any application program or
java application with the data base.
Jdbc used to interact with various databases. It can define
platform independent b/w a relational db and java programs.
It can develop an application in a one system and run in any
other systems because of platform independent.
We can also manipulate data from the database with the help of
•user: Username from which your SQL command prompt can be accessed.
•password: password from which the SQL command prompt can be accessed.
•con: It is a reference to the Connection interface.
•Url: Uniform Resource Locator which is created as shown below:
String url = “ jdbc:oracle:thin:@localhost:1521:xe”
Where oracle is the database used, thin is the driver used, @localhost is the IP Address
where a database is stored, 1521 is the port number and xe is the service provider. All 3
parameters above are of String type and are to be declared by the programmer before calling
the function. Use of this can be referred to form the final code.
Java Database Connectivity with MySQL
To connect Java application with the MySQL database, we need to follow
5 following steps.
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.
We interact with a data source through sessions. Each connection identifies a
logical session.
JDBC URL: jdbc:<subprotocol>:<otherParameters>
Example:
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.getMessageO);
return;
Connection Class Interface
The Connection interface provide many methods for transaction management like commit(), rollback(),
setAutoCommit(), setTransactionIsolation(), etc
If autocommit is set, then each SQL statement is considered its own transaction. Otherwise, a transaction is
committed using commit(), or aborted using rollback().
4) public void commit(): saves the changes made since the previous commit/rollback is
permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources
immediately.
Connection Interface Fields
There are some common Connection interface constant fields that are present in the
Connect interface. These fields specify the isolation level of a transaction.
TRANSACTION_NONE: No transaction is supported, and it is indicated by this
constant.
TRANSACTION_READ_COMMITTED: It is a constant which shows that the dirty
reads are not allowed. However, phantom reads and non-repeatable reads can occur.
TRANSACTION_READ_UNCOMMITTED: It is a constant which shows that dirty
reads, non-repeatable reads, and phantom reads can occur.
TRANSACTION_REPEATABLE_READ: It is a constant which shows that the non-
repeatable reads and dirty reads are not allowed. However, phantom reads and can occur.
TRANSACTION_SERIALIZABLE: It is a constant which shows that the non-
repeatable reads, dirty reads as well as the phantom reads are not allowed.
Executing SQL Statements
In JDBC Three different ways of executing SQL statements:
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.
Statement (both static and dynamic SQL statements)
PreparedStatement
CallableStatment
Structure is fixed
Values of parameters are determined at run-time
The Connection interface is a factory of Statement,
PreparedStatement, and DatabaseMetaData, i.e., an object of
Connection can be used to get the object of Statement and
DatabaseMetaData
Commonly used methods of Connection interface:
1) public Statement createStatement(): creates a
statement object that can be used to execute SQL
queries.
2) public Statement createStatement(int
resultSetType,int
resultSetConcurrency): Creates a Statement
object that will generate ResultSet objects with the
given type and concurrency.
Consider the sample code using a PreparedStatment object
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 statements, as in Figure 6.3.
The method setString is one way to set a parameter
value. It is good style to always use clearParameters ( )
before setting parameter values in order to remove any
old data.
There are different ways of submitting the query
string to the data source.
we used the executeUpdate command, which is
used if we know that the SQL statement does not
return any records.
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.
Executing SQL Statements
(Contd.)
String sql=“INSERT INTO Sailors VALUES(?,?,?,?)”;
PreparedStatment pstmt=con.prepareStatement(sql);
pstmt.clearParameters();
pstmt.setInt(1,sid);
pstmt.setString(2,sname);
pstmt.setInt(3, rating);
pstmt.setFloat(4,age);
SQLJ provides strong typing of query outputs and return parameters and
allows type-checking on calls. JDBC passes values to and from SQL
without compile-time type checking.
SQLJ provides simplified rules for calling SQL stored procedures and
functions.
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 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
};
SQLJ code fragment that selects records from the Books table that match a given author.
String title; Float price; String atithor;
#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();
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 ancl execute it
stmt.setString(1, author);
ResultSet 1'8 = stmt.executeQuery();
/ / retrieve the results
while (rs.next()) {
System.out.println(rs.getString(l) + ", " + rs.getFloat(2));
}
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
// SQLJ
int n;
#sql { INSERT INTO emp VALUES (:n)};
// JDBC
int n;
Statement stmt = conn.prepareStatement (“INSERT INTO emp VALUES
(?)”);
stmt.setInt(1,n);
stmt.execute ();
stmt.close();
SQLJ Code
Int sid; String name; Int rating;
// named iterator
#sql iterator Sailors(Int sid, String name, Int rating);
Sailors sailors;
// assume that the application sets rating
#sailors = {
SELECT sid, sname INTO :sid, :name
FROM Sailors WHERE rating = :rating
};
// retrieve results
while (sailors.next()) {
System.out.println(sailors.sid + “ “ + sailors.sname));
}
sailors.close();
SQLJ Iterators
Two types of iterators (“cursors”):
Named iterator
Need both variable type and name, and then allows retrieval of columns by
name.
See example on previous slide.
Positional iterator
Need only variable type, and then uses FETCH .. INTO construct:
#sql iterator Sailors(Int, String, Int);
Sailors sailors;
#sailors = …
while (true) {
#sql {FETCH :sailors INTO :sid, :name} ;
if (sailors.endFetch()) { break; }
// process the sailor
}
Open DataBase Connectivity
Shorten to ODBC, a standard database access method
The goal: make it possible to access any data from any application,
regardless of which (DBMS).
For this to work, both the application and the DBMS must be
ODBC-compliant -- that is, the application must be capable of
issuing ODBC commands and the DBMS must be capable of
responding to them.
Stored Procedures
What is a stored procedure:
Program executed through a single SQL statement
Executed in the process space of the server
Advantages:
Can encapsulate application logic while staying
“close” to the data
Reuse of application logic by different users
Avoid tuple-at-a-time return of records through cursors
Stored Procedures: Examples
The local variable declarations were empty, and the procedure code consisted
of an SQL query.
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;
We can declare local variables using the DECLARE
statement. In our example,
we declare two local variables: 'rating', and 'numOrders'.
PSM/SQL functions return values via the RETURN
statement. In our example,
we return the value of the local variable 'rating'.
we can assign values to variables with the SET
statement. In our example,
we assigned the return value of a query to the variable
'numOrders'.