8/8/2019 JDBC_Session02
1/39
Slide 1 of 39Session 2Ver. 1.0
JDBC
In this session, you will learn to:
Create applications using the PreparedStatement object
Manage database transactions
Perform batch updates
Create and call stored procedures in JDBC
Use metadata in JDBC
Objectives
8/8/2019 JDBC_Session02
2/39
Slide 2 of 39Session 2Ver. 1.0
JDBC
The PreparedStatement interface is derived from the
Statement interface and is available in the java.sql
package.
The PreparedStatement object:
Allows you to pass runtime parameters to the SQL statementsto query and modify the data in a table.
Is compiled and prepared only once by JDBC. The futureinvocation of the PreparedStatement object does not
recompile the SQL statements.
Helps in reducing the load on the database server and thus
improving the performance of the application.
Create Applications Using the PreparedStatement Object
8/8/2019 JDBC_Session02
3/39
Slide 3 of 39Session 2Ver. 1.0
JDBC
The PreparedStatement interface inherits the following
methods to execute SQL statements from the Statement
interface:
ResultSet executeQuery(): Executes a SELECT
statement and returns the result in a ResultSet object.int executeUpdate(): Executes an SQL statement,
INSERT, UPDATE, orDELETE and returns the count of the
rows affected.
boolean execute(): Executes an SQL statement and
returns a boolean value.
Methods of the PreparedStatement Interface
8/8/2019 JDBC_Session02
4/39
Slide 4 of 39Session 2Ver. 1.0
JDBC
The prepareStatement() method of the Connection
object is used to submit parameterized query to a database.
The SQL statement can contain ? symbol as placeholders
that can be replaced by input parameters at runtime. For
example:stat=con.prepareStatement("SELECT * FROM
Authors WHERE au_id = ?");
Methods of the PreparedStatement Interface (Contd.)
8/8/2019 JDBC_Session02
5/39
Slide 5 of 39Session 2Ver. 1.0
JDBC
The value of each ? parameter is set by calling an
appropriate setXXX() method, where xxx is the data type of
the parameter. For example:
stat.setString(1,a001");
ResultSet result=stat.executeQuery();
Methods of the PreparedStatement Interface (Contd.)
8/8/2019 JDBC_Session02
6/39
Slide 6 of 39Session 2Ver. 1.0
JDBC
The code snippet to retrieve books written by an author fromthe books table using the PreparedStatement object is:
String str = "SELECT * FROM books WHERE
au_id = ?";
PreparedStatement ps=con.prepareStatement(str);
ps.setString(1, a001");
ResultSet rs=ps.executeQuery();
Retrieving Rows
8/8/2019 JDBC_Session02
7/39
Slide 7 of 39Session 2Ver. 1.0
JDBC
The code snippet to create a PreparedStatement object
that inserts a row into authors table by passing authors data
at run time is:
String str = "INSERT INTO Authors(au_id,
au_name) VALUES (?, ?)";PreparedStatement ps =
con.prepareStatement(str);
ps.setString(1, a001");
ps.setString(2, "Abraham White");
int rt=ps.executeUpdate();
Inserting Rows
8/8/2019 JDBC_Session02
8/39
Slide 8 of 39Session 2Ver. 1.0
JDBC
The code snippet to modify the state to CA where city is
Oakland in the Authors table using thePreparedStatement object is:
String str = "UPDATE Authors SET state= ?
WHERE city= ? ";PreparedStatement ps =
con.prepareStatement(str);
ps.setString(1, "CA");
ps.setString(2, "Oakland");
int rt=ps.executeUpdate();
Updating and Deleting Rows
8/8/2019 JDBC_Session02
9/39
Slide 9 of 39Session 2Ver. 1.0
JDBC
The code snippet to delete a row from the Authors table
where authors name is Abraham White using thePreparedStatement object is:
String str = "DELETE FROM Authors WHERE
au_name= ? ";PreparedStatement ps =
con.prepareStatement(str);
ps.setString(1, "Abraham White");
int rt=ps.executeUpdate();
Updating and Deleting Rows (Contd.)
8/8/2019 JDBC_Session02
10/39
Slide 10 of 39Session 2Ver. 1.0
JDBC
Just a minute
Name the three methods of the PreparedStatement
Interface.
Answer:The three methods of the PreparedStatement Interface are:
1. ResultSet executeQuery()
2. int executeUpdate()
3. Boolean execute()
8/8/2019 JDBC_Session02
11/39
Slide 11 of 39Session 2Ver. 1.0
JDBC
Problem Statement:
The management of the City Library has decided to
computerize the book inventory. You have been asked to
create the Publisher Information application that has an
interactive user interface. The application should allow the user
to add the details of the new publishers to the publishers table.
Demonstration
8/8/2019 JDBC_Session02
12/39
Slide 12 of 39Session 2Ver. 1.0
JDBC
A sample of the user interface is shown in the following fugure.
Demonstration (Contd.)
8/8/2019 JDBC_Session02
13/39
Slide 13 of 39Session 2Ver. 1.0
JDBC
To insert information about a new publisher in the publishers
table:
1. Specify the id for a publisher in the ID textbox and publishers
details, such as name, phone, address, city, state, and zip in the
respective text boxes.
2. Click the Insert button to insert information.
3. To exit from the application, click the Exit button.
Demonstration (Contd.)
8/8/2019 JDBC_Session02
14/39
Slide 14 of 39Session 2Ver. 1.0
JDBC
Solution:
To solve the problem, you need to perform the following tasks:
1. Code the application.
2. Compile and execute the application.
Demonstration (Contd.)
8/8/2019 JDBC_Session02
15/39
Slide 15 of 39Session 2Ver. 1.0
JDBC
A transaction:
Is a set of one or more SQL statements that are executed as a
single unit.
Is complete only when all the SQL statements in a transaction
execute successfully.Maintains consistency of data in a database.
ManagingDatabase Transactions
8/8/2019 JDBC_Session02
16/39
Slide 16 of 39Session 2Ver. 1.0
JDBC
JDBC API provides support for transaction management.
The database transactions can be committed in two ways in
the JDBC applications:
Implicit: The Connection object uses the auto-commit mode
to execute the SQL statements implicitly.Explicit: The auto-commit mode is set to false to commit the
transaction statement explicitly.The method call to set the
auto-commit mode to false is:
con.setAutoCommit(false);
ManagingDatabase Transactions (Contd.)
8/8/2019 JDBC_Session02
17/39
Slide 17 of 39Session 2Ver. 1.0
JDBC
The commit() method is used to reflect the changes made
by the transactions in a database.
The rollback() method is used to undo the changes
made in the database after the last commit operation.
You need to explicitly invoke commit() and rollback()methods.
Committing a Transaction
8/8/2019 JDBC_Session02
18/39
8/8/2019 JDBC_Session02
19/39
Slide 19 of 39Session 2Ver. 1.0
JDBC
A batch:
Is a group of update statements that are sent to a database to
be executed as a single unit.
Reduces network calls between the application and the
database.Is a more efficient way as compared to the processing of a
single SQL statement.
Implementing Batch Updates in JDBC
8/8/2019 JDBC_Session02
20/39
Slide 20 of 39Session 2Ver. 1.0
JDBC
The Statement orPreparedStatement interface
provides the following methods to create and execute a
batch of SQL statements:
void addBatch(): Adds an SQL statement to a batch.
int executeBatch(): Sends a batch of SQL statements toa database for processing and returns the total number of the
rows updated.
void clearBatch(): Removes the SQL statements from
the batch.
Implementing Batch Updates in JDBC (Contd.)
8/8/2019 JDBC_Session02
21/39
Slide 21 of 39Session 2Ver. 1.0
JDBC
The code snippet to create a batch of SQL statements is:
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.addBatch("INSERT INTO Publishers
(pub_id, pub_name) VALUES (p001,TatePublishing')");
stmt.addBatch("INSERT INTO Publishers
(pub_id, pub_name) VALUES (p002, Publish
America')");
The SQL statements in a batch are processed in the order inwhich the statements appear in a batch.
The method call to execute a batch of SQL statements is:
int[] updcount=stmt.executeBatch();
Implementing Batch Updates in JDBC (Contd.)
8/8/2019 JDBC_Session02
22/39
Slide 22 of 39Session 2Ver. 1.0
JDBC
The batch update operations can throw two types of
exceptions:
SQLException
BatchUpdateException
The BatchUpdateException class is derived from theSQLException class.
Exception Handling in Batch Updates
8/8/2019 JDBC_Session02
23/39
Slide 23 of 39Session 2Ver. 1.0
JDBC
The SQLException is thrown by the JDBC API methods,
addBatch() orexecuteBatch(), when problem occurs
while accessing a database.
The BatchUpdateException exception is thrown when
the SQL statements in the batch cannot be executed due to:Presence of illegal arguments in the SQL statement.
Absence of the database table from which you need to retrieve
data.
The BatchUpdateException uses an array of the update
count to identify the SQL statement that throws theexception.
Exception Handling in Batch Updates (Contd.)
8/8/2019 JDBC_Session02
24/39
Slide 24 of 39Session 2Ver. 1.0
JDBC
The java.sql package provides the
CallableStatement interface that contains various
methods to enable you to call the stored procedures from a
database.
The CallableStatement interface is derived from thePreparedStatement interface.
Creating and Calling Stored Procedures in JDBC
8/8/2019 JDBC_Session02
25/39
Slide 25 of 39Session 2Ver. 1.0
JDBC
Can be created using the CREATE PROCEDURE SQL
statement in JDBC applications.
Are of two types:
Parameterized
Non-parameterized
Creating Stored Procedures
8/8/2019 JDBC_Session02
26/39
Slide 26 of 39Session 2Ver. 1.0
JDBC
A parameterized stored procedure can accept one or
multiple parameters.
A parameter of a stored procedure can take any of these
forms:
IN: Refers to the argument that you pass to a storedprocedure.
OUT: Refers to the return value of a stored procedure.
INOUT: Combines the functionality of the IN and OUT
parameters. The INOUT parameter enables you to pass an
argument to a stored procedure. The same parameter can also
be used to store a return value of a stored procedure.
Creating Stored Procedures (Contd.)
8/8/2019 JDBC_Session02
27/39
Slide 27 of 39Session 2Ver. 1.0
JDBC
The Connection interface provides the prepareCall()
method that is used to create the CallableStatement
object to call a stored procedure.
The prepareCall() has the following three forms:
CallableStatement prepareCall(String str)CallableStatement prepareCall(String str, int
resSetType, int resSetConcurrency)
CallableStatement prepareCall(String str, int
resSetType, int resSetConcurrency, int
resSetHoldability)
The syntax to call a stored procedure without parameters is:
{ call };
Calling a Stored Procedure Without Parameters
8/8/2019 JDBC_Session02
28/39
8/8/2019 JDBC_Session02
29/39
Slide 29 of 39Session 2Ver. 1.0
JDBC
The placeholders are used to represent the IN, OUT, and
INOUT parameters of a stored procedure in the procedure
call.
The syntax to call a stored procedure with parameters is:
{ call (?) };You need to set the value of the IN parameters using the
set methods before the CallableStatement object is
executed.
The syntax to set the value of the IN parameter is:
.setInt();
Calling a Stored Procedure with Parameters (Contd.)
8/8/2019 JDBC_Session02
30/39
Slide 30 of 39Session 2Ver. 1.0
JDBC
If the stored procedure contains OUT and INOUT
parameters, these parameters should be registered with the
corresponding JDBC types.
The registerOut() method is used to register the
parameters.The prototypes of the registerOut() method are:
registerOut(int index, int stype)
registerOut(int index, int stype, int scale)
Calling a Stored Procedure with Parameters (Contd.)
8/8/2019 JDBC_Session02
31/39
Slide 31 of 39Session 2Ver. 1.0
JDBC
Metadata is the information about data, such as structure
and properties of table.
The metadata of the employee table includes following
information:
Names of the columns.Data type of each column.
Constraints to enter data values in the table columns.
JDBC API provides the following two metadata interfaces to
retrieve the information about the database and result set:
DatabaseMetaData interfaceResultSetMetaData interface
Using Metadata in JDBC
8/8/2019 JDBC_Session02
32/39
Slide 32 of 39Session 2Ver. 1.0
JDBC
The DatabaseMetaData interface provides the methods that
enable you to determine the properties of a database or
RDBMS.
An object ofDatabaseMetaData is created using the
getMetaData() method of the Connection interface.The method call to create an object of theDatabaseMetaData interface is:
DatabaseMetaData dm=con.getMetaData();
Using the DatabaseMetadata Interface
8/8/2019 JDBC_Session02
33/39
Slide 33 of 39Session 2Ver. 1.0
JDBC
The ReultSetMetaData Interface contains various
methods that enable you to retrieve information about the
data in a result set.
The ResultSet interface provides the getMetaData()
method to create an object of the ResultSetMetaDatainterface.
The method call to create an object of theResultSetMetaData interface:
ResultSetMetaData rm=rs.getMetaData();
Using the ResultMetadata Interface
8/8/2019 JDBC_Session02
34/39
Slide 34 of 39Session 2Ver. 1.0
JDBC
Just a minute
What are the metadata interfaces used to retrieve
information about the database and result set?
Answer:The metadata interfaces used to retrieve information about the
database and result set are:
1. DatabaseMetaData interface
2. ResultSetMetaData interface
8/8/2019 JDBC_Session02
35/39
Slide 35 of 39Session 2Ver. 1.0
JDBC
Problem Statement:
The Manager ofNew Publishers publishing company,
sometimes require the information about the tables of the
database used by the company. He is not familiar with the SQL
statements, therefore, he has asked you to create an
application to determine the total number of columns and the
data types of the columns of a given table. The table name has
to be specified at the run time.
Demonstration
8/8/2019 JDBC_Session02
36/39
Slide 36 of 39Session 2Ver. 1.0
JDBC
Solution:
To solve the Preceding problem, perform the following tasks:
1. Code the application.
2. Pass the command line argument.
3. Compile and execute the application.
Demonstration (Contd.)
8/8/2019 JDBC_Session02
37/39
Slide 37 of 39Session 2Ver. 1.0
JDBC
In this session, you learned that:
The PreparedStatement object allows you to pass runtime
parameters to the SQL statements using the placeholders.
There can be multiple placeholders in a single SQL statement.
An index value is associated with each placeholder depending
upon the position of the placeholder in the SQL statement.
The placeholder stores the value assigned to it until the value
is explicitly changed.
A transaction is a set of one or more SQL statements that are
executed as a single unit. A transaction is complete only when
all the SQL statements in a transaction are successfullyexecuted.
If the setAutoCommit() method is set to true the database
operations performed by the SQL statements are automatically
committed in the database.
Summary
8/8/2019 JDBC_Session02
38/39
Slide 38 of 39Session 2Ver. 1.0
JDBC
The commit() method reflects the changes made by the SQL
statements permanently in the database.
The rollback() method is used to undo the effect of all the
SQL operations performed after the last commit operation.
A batch is a group of update statements that are sent to a
database to be executed as a single unit. You send the batch
to a database as a single request using the sameConnection object.
Batch update operations can throw two types of exceptions,
SQLException and BatchUpdateException.
The SQLException is thrown when the database accessproblem occurs. The SQLException is also thrown when a
SELECT statement that returns a ResultSet object is executed
in a batch.
Summary (Contd.)
8/8/2019 JDBC_Session02
39/39
Slide 39 of 39Session 2Ver. 1.0
JDBC
The BatchUpdateException is thrown when the SQL
statement in the batch cannot be executed due to the problem
in accessing the specified table or presence of illegal
arguments in the SQL statement.
The CallableStatement interface contains various methods
that enable you to call the stored procedures from a database.
Metadata is the information about data, such as structure and
properties of table
JDBC API provides two metadata interfaces to retrieve the
information about the database and result set,
DatabaseMetaData and ResultSetMetaData
Summary (Contd.)