2. Java and the database
• Database is used to store data. It is also
known as persistent storage as the data is
stored and can be retrieved anytime.
• Java and database are used almost
everywhere to store persistent data and
retrieve it when required.
3. SQL
• Information stored in the database is in tables
and the language used to query information
from the database is SQL.
• Using SQL we can query a table based on the
requirement.
4. DDL – DML – DCL - TCL
• DDL – Data Definition Language
– These queries are used to create database objects such as
tables, indexes, procedures, constraints
– Create , drop, alter,truncate,comment,rename
• DML – Data Manipulation Language
– These queries are used to manipulate the data in the database
tables.
– Insert, update, delete, select (more available)
• DCL – Data Control Language
– These are data control queries like grant and revoke
permissions
• TCL– Transaction Control Language
– These are transaction control queries like commit, revoke,
savepoint, set transaction
5. What is JDBC?
• JDBC provides Java applications with access to most database
systems via SQL
• The architecture and API closely resemble Microsoft's ODBC
• JDBC 1.0 was originally introduced into Java 1.1
– JDBC 2.0 was added to Java 1.2
• JDBC is based on SQL-92
• JDBC classes are contained within the java.sql package
– There are few classes
– There are several interfaces
6. Database Connectivity History
Before APIs like JDBC and ODBC,
database connectivity was tedious
• Each database vendor provided a function library for accessing
their database
• The connectivity library was proprietary.
• If the database vendor changed for the application, the data access
portions had to be rewritten
• If the application was poorly structured, rewriting its data access
might involve rewriting the majority of the application
• The costs incurred generally meant that application developers
were stuck with a particular database product for a given
application
7. JDBC Architecture
• With JDBC, the application programmer uses the JDBC API
– The developer never uses any proprietary APIs
• Any proprietary APIs are implemented by a JDBC driver
• There are 4 types of JDBC Drivers
Java Application
JDBC API
JDBC DriverManager
JDBC Driver JDBC Driver
8. JDBC Drivers
• Type 1 Driver - JDBC-ODBC bridge
– This is an ODBC driver, which is open source
• Type 2 Driver – Native API driver
– This is more like the OCI (Oracle Call Interface) call
interface is converted to native calls of the database.
• Type 3 Driver – Network protocol driver
– This is achieved by using a Java Driver in a middleware
• Type 4 Driver – Native Protocol Driver
– This is a driver written purely in Java Language
• We Usually prefer to depend on the Type 4 driver
– Eg: Oracle thin driver
9. Java-Oracle Example
public void ConnectToAndQueryDatabase
(String username, String password)
{
Connection con =
DriverManager.getConnection( "jdbc:myD
river:myDatabase", username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT
a, b, c FROM Table1");
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}
}
•In the example we have a method call
ConnectTo And QueryDatabase which
takes in a username, password
•The Connection Interface creates a
connection. A connection is created by
using the DriverManager Class with the
connection string , username, password.
The concrete implementation is
OracleConnection.
•The statement Interface creates a
statement. The concrete implementation
is Oracle Statement.
•ResultSet stores the result after invoking
execute Query on the statement object.
We can iterate over the resultset to get
the results from table.
10. Statement and Prepared
Statement
• A Statement Interface is used to create a statement i.e.
a query to be executed against a database. In this
process, two calls are made to the database system ,
one to get the table metadata and other to get the
data itself. The statement object is also compiled every
time it executes.
• A Prepared statement comes in handy as it is compiled
and cached and only makes on database call when
invoked. The compilation would be skipped even if the
values in the where clause change
11. Statement and Prepared
Statement• Statement
Statement stmt= con.statment(“select * from mytab where num=22”);
• Prepared Statement
PreparedStatement pstmt = con.preparestatement(select * from mytab where num=?”);
pstmt.setInt(1,”11”);
This sets the value of ? as 11
– If we run the statement in for loop every time
changing the where clause, the statement is
compiled every time before execution.
– In the case of prepared statement , the prepared
statement is cached and compiled only one time in
the event of a for loop with changing where clause.
12. Stored Procedures
• Stored procedures are compiled sql programs
which are stored in the database system and
can be executed in the database.
• We use the call keyword in SQL to execute
stored procedures
• Java can access the stored procedures in the
database by using the Callable statements
13. Callable Statements
• Callable statements are used to call stored
procedures in the database.
CallableStatement cstmt = null;
try {
String SQL = "{call myprocedure(?, ?)}"; //? Can be set dynamically as in
prepared statement
cstmt = conn.prepareCall (SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}
14. JDBC Interfaces
• ResultSet
– Represents the result of an SQL statement
– Provides methods for navigating through the resulting data
• DatabaseMetaData
– Provides access to a database's system catalogue
• ResultSetMetaData
– Provides information about the data contained within a ResultSet
15. Transactions
• Transactions imply a situation when we have one
or more SQL statements to be committed only
when everything goes right
– Assume we have 10 databases which are always to be
in sync. So we would have one sql query to be
executed across all databases. So, the sql query
should committed in all the databases only after
successful execution in all 10 databases. This is called
a transaction. The transaction is committed only after
successful execution across all databases.
16. Closing Connections
• Always remember to close in the following
sequence.
– Resultset
– Statement/Prepared Statement
– Connections
• Do a null check always before closing the
connections using close() method.