Unit 2 - JDBC
Unit 2 - JDBC
Java
JDBC
Application DATABASE
Oracle,DB2,Postgre,Sybase,MySQL,
SQLite, Apache Cassandra, MS Access
• JDBC Is a part of Java Standard Edition.
• JAVA editions are
▪ Java Standard Edition
▪ Java Enterprise Edition
▪ Java Micro Edition
• JDBC is a Specification defined by Java Vendor and implemented
by Database vendor.
• Database vendor provided implementation is Driver Software.
Introduction
Database
◦ Collection of data
DBMS
◦ Database management system
◦ Storing and organizing data
SQL
◦ Relational database
◦ Structured Query Language
JDBC
◦ Java Database Connectivity
◦ JDBC driver
• JDBC is a Sun Microsystems trademark
• It is often taken to stand for Java Database Connectivity
OD JD
C,C++ , Java
BC Java BC
win Completel
Any
Native Platfor
Languages dow y Java
m
s
ODBC
Open Data Base Connectivity
Developed by Microsoft for the Windows platform as the way for
Windows applications to access Microsoft databases (SQL Server, FoxPro,
Ms.Access)
Most data base vendors supply native, odbc, and jdbc drivers for their
data base products
ODBC provides a C interface for database access on Windows
environment.
ODBC has a few commands with lots of complex options. Java prefers
simple methods.
Two-Tier Database Access Model
Java Application talks directly Application Space
to the database
Accomplished through the Java Application
JDBC driver which sends
commands directly to the
database JDBC Driver
Database
Three-Tier Database Access Model
• Driver
• Translates API calls into operations for a specific data source
• Connection
• A session between an application and a database
JDBC Component Interaction
1. getConnection() 2. createStatement()
Driver
Creates Connection Creates Statement Creates ResultSet
Manager
SQL
SQL
3a. select -> executeQuery() Driver
3b. Insert/Update/Delete Establish
executeUpdate() Link to DB Result
(tuples)
Database
STEPS Using JDBC
The following steps are executed when running a JDBC application
• Import the necessary classes (JDBC Packages – java.sql)
• Load the JDBC driver
• Identify the database source
• Obtain a “Connection” object (create) to the database (Create a Connection)
• Obtain a “Statement” object (create)
• Execute a query using the “Statement” object
• Updates, inserts and deletes return Boolean. Selects return a ResultSet
• Retrieve data from the returned “ResultSet” object
• Close the “ResultSet” object
• Close the “Statement” object
• Close the “Connection” object
Do NOT close the connection
The same connection object can be used to create further
statements
java.sql.DriverManager
◦ Maintains a list of Driver implementations and presents an application
with one that matches a requested URL.
◦ getConnection(url, uid, password)
◦ getDrivers(), registerDriver()
java.sql.Connection
◦ Represents a single logical DB connection; used for sending SQL
statements
JDBC – Making the Connection
java.sql.Statement
◦ Most basic class. It performs all the SQL statements
◦ executeQuery( String )
◦ executeUpdate( String )
◦ execute( String )
java.sql.ResultSet
◦ One or more rows of data returned by a query
Statement st = c.createStatement();
ResultSet rs = st.executeQuery(“…”);
JDBC – Database Access Classes
◦ Methods: next(),getString(column),getInt(..),
last(), getRow()
java.sql.DatabaseMetaData
◦ Provides extra information about the database for a given connection object
◦ What tables exist, what username is being used, is the DB read-only, what are
the primary keys for a table, etc.
DatabaseMetaData dmd = c.getMetaData();
◦ Lets developers write apps that are DB-independent
Steps Involved in Basic JDBC Operations
Driver Manager
1. Load the JDBC driver class:
Class.forName(“driverName”); Driver
2. Open a database connection:
DriverManager.getConnection
(“jdbc:xxx:datasource”); Connection Database
Database
Type 3 Type 2 Native C/C++ API
Local API
Network API
Type 4
• Type 1: Uses a bridging technology to access a database. JDBC-ODBC bridge is an example. It provides a gateway
to the ODBC.
• Type 2: Native API drivers. Driver contains Java code that calls native C/C++ methods provided by the database
vendors.
• Type 3: Generic network API that is then translated into database-specific access at the server level. The JDBC
driver on the client uses sockets to call a middleware application on the server that translates the client requests into
an API specific to the desired driver. Extremely flexible.
• Type 4: Using network protocols built into the database engine talk directly to the database using Java sockets.
Almost always comes only from database vendors.
JDBC STATEMENTS
⮚Once a connection is obtained we can interact with the
database.
⮚Following Interfaces define the methods and properties that
enable you to send SQL or PL/SQL commands and receive data
from your database.
1. The JDBC Statement
2. PreparedStatement
3. CallableStatement
1. JDBC STATEMENT(STATEMENT OBJECT)
⮚ Before you can use a Statement object to execute a SQL statement, you need to
create one using the Connection object's createStatement( ) method,
Statement stmt = null;
try {
stmt = conn.createStatement( );
}
Catch(Exception e){
}
⮚Once you've created a Statement object, you can then use it to execute an SQL statement with
one of its three execute methods.
1. boolean execute (String SQL)
2. int executeUpdate (String SQL)
3. ResultSet executeQuery (String SQL)
************************************************************
PRODUCT INFORMATION
************************************************************
1… Insert New Product
2… Update Existing Product
3… Search Product
4… Delete Product
5… Display All Products
STORED PROCEDURE
IN OUT Parameter:
•This parameter is used for both giving input and for getting output from the
subprograms.
•It is a read-write variable inside the subprograms. Their values can be
changed inside the subprograms.
•In the calling statement, these parameters should always be a variable to
hold the value from the subprograms
PARAMETERS IN STORED PROCEDURE
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR);
cstmt.execute();
cstmt.close();
conn.close();
} catch (SQLException e) {
⮚Using the CallableStatement objects is much like using the PreparedStatement objects. You
must bind values to all the parameters before executing the statement
⮚If you have IN parameters, just follow the same rules and techniques that apply to a
PreparedStatement object; use the setYYY() method
⮚When you use OUT and INOUT parameters you must employ an additional
CallableStatement method, registerOutParameter(). The registerOutParameter() method
binds the JDBC data type, to the data type that the stored procedure is expected to return
⮚Once you call your stored procedure, you retrieve the value from the OUT parameter with
the appropriate getXXX() method
TRANSACTIONS AND JDBC
▪ JDBC allows SQL statements to be grouped together into a single transaction
A transaction is a unit of work that is performed against a database.
Transaction control is performed by the Connection object, default mode is auto-
commit mode, I.e., each sql statement is treated as a transaction
To enable manual- transaction ,We can turn off the auto-commit mode with
con.setAutoCommit(false);
And turn it back on with con.setAutoCommit(true);
Once auto-commit is off, no SQL statement will be committed until an explicit is
invoked con.commit();
At this point all changes done by the SQL statements will be made permanent in the
database.
50
TRANSACTIONS
⮚Transactions enable you to control if, and when, changes are applied to
the database
⮚All data base transactions are by default in auto-commit mode
⮚To enable manual- transaction support instead of the auto-commit
mode that the JDBC driver uses by default, use the Connection object's
setAutoCommit() method. If you pass a boolean false to
setAutoCommit( ), you turn off auto-commit. You can pass a boolean
true to turn it back on again.
⮚Example:
⮚conn.setAutoCommit(false);
Transactions enable you to control if, and when, changes are applied to the
database
The following commands are used to control transactions.
⮚COMMIT − to save the changes. The COMMIT command saves all the transactions to the
database. Once you are done with your changes and you want to commit (Save) the changes
then call commit() method on connection object as follows
con.commit( );
ROLLBACK − to roll back the changes, used to undo transactions that have not already been
saved to the database. This command can only be used to undo transactions since the last
COMMIT or ROLLBACK command was issued.
con.rollback( );
commit
Initial State
rollback
Transaction failed
COMMIT, ROLLBACK AND SAVEPOINT
⮚If we enable manual transaction supportin the in SQL statement
execution then Commit, Rollback and Savepoint plays an important role
⮚Once you are done with your changes and you want to commit (Save)
the changes then call commit() method on connection object as follows
conn.commit( );
⮚to roll back updates to the database made using the Connection named
conn
conn.rollback( );
⮚When you set a savepoint you define a logical rollback point within a
transaction. If an error occurs past a savepoint, you can use the rollback
method to undo either all the changes or only the changes made after
the savepoint.
// Rollback to savepoint
conn.rollback(savepoint);
BATCH PROCESSING