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

Creating Applications Using Advanced Features of JDBC

Uploaded by

SURYA SUMEET
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Creating Applications Using Advanced Features of JDBC

Uploaded by

SURYA SUMEET
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Creating Applications Using the

PreparedStatement Object
Consider a scenario where New Publishers, a
publishing house, maintains details about books
and authors in a database. The management of
New Publishers wants an application that can help
them access the details about authors based on
different criteria.

For example,

the application should be able to retrieve the


details of all the authors living in a particular city
specified at runtime. In this scenario, you cannot
use the Statement object to retrieve the details
because the value for the city needs to be
specified at runtime. You need to use the
PreparedStatement object as it can accept
runtime parameters.
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
statements to query and modify the data in a
table.

The PreparedStatement objects are compiled


and prepared only once by JDBC. The further
invocation of the PreparedStatement object
does not recompile the SQL statements. This
helps in reducing the load on the database
server and improves the performance of the
application
Methods of the PreparedStatement
Interface
The PreparedStatement interface inherits the
following methods to execute the SQL statements
from the Statement interface:

 ResultSet executeQuery(): Is used to execute the


SQL statement and returns the result in a
ResultSet object.

 int executeUpdate(): Executes an SQL statement,


such as INSERT, UPDATE, or DELETE, and returns
the count of the rows affected.

 boolean execute(): Executes an SQL statement and


returns the boolean value.
Consider an example where you have to retrieve the details of
an author by passing the author id at runtime. For this, the
following SQL statement with a parameterized query can be
used:

SELECT * FROM Authors WHERE au_id = ?


To submit such a parameterized query to a database from an
application, you need to create a PreparedStatement object
using the prepareStatement() method of the Connection object.
You can use the following code snippet to prepare an SQL
statement that accepts values at runtime:

stat=con.prepareStatement("SELECT * FROM Authors WHERE


au_id = ?");
The prepareStatement() method of the Connection object takes
an SQL statement as a parameter. The SQL statement can
contain the symbol, ?, as a placeholder that can be replaced by
input parameters at runtime.

Before the SQL statement specified in the PreparedStatement


object is executed, you must set the value of each ? parameter.
The value can be set by calling an appropriate setXXX() method,
where XXX is the data type of the parameter. For example,
consider the following code snippet:

stat.setString(1,"A001");
ResultSet result=stat.executeQuery();

In the preceding code snippet, the first


parameter of the setString()method specifies the
index value of the ? placeholder, and the second
parameter is used to set the value of the ?
placeholder.

You can use the following code snippet when the


value for the ? placeholder is obtained from the
user interface:

stat.setString(1,aid.getText());
ResultSet result=stat.executeQuery();

In the preceding code snippet, the setString()


method is used to set the value of the ?
placeholder with the value retrieved at runtime
from the aid textbox of the user interface.
The PreparedStatement interface provides various
methods to set the value of placeholders for the
specific data types. The following table lists some
commonly used methods of the PreparedStatement
interface.
Retrieving Rows
You can use the following code snippet to retrieve the
details of the books written by an author from the
Books table by using the PreparedStatement object:

String str = "SELECT * FROM Books WHERE au_id = ?";


PreparedStatement ps= con.prepareStatement(str);
ps.setString(1, "A001");
ResultSet rs=ps.executeQuery();

while(rs.next())
{
System.out.println(rs.getString(1) + " " + rs.getString(2));
}

In the preceding code snippet, the str variable stores


the SELECT statement that contains one input
parameter. The setString() method is used to set the
value for the au_id attribute of the Books table. The
SELECT statement is executed using the executeQuery()
method, which returns a ResultSet object.
Inserting Rows
You can use the following code snippet to create a
PreparedStatement object that inserts a row into the
Authors table by passing the author’s data at runtime:

String str = "INSERT INTO Authors (au_id, au_name)


VALUES (?,?)";

PreparedStatement ps = con.prepareStatement(str);
ps.setString(1, "1001");
ps.setString(2, "Abraham White");
int rt=ps.executeUpdate();

In the preceding code snippet, the str variable stores the


INSERT statement that contains two input parameters.

The setString() method is used to set the values for the


au_id and au_name columns of the Authors table.
The INSERT statement is executed using the
executeUpdate() method, which returns an integer value
that specifies the number of rows inserted into the table.
Updating Rows
You can use the following code snippet to modify the
state to CA where city is Oakland in the Authors
table by using the PreparedStatement object:

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();

In the preceding code snippet, two input parameters


, state and city, contain the values for the state and
city attributes of the Authors table, respectively.
Deleting Rows
You can use the following code snippet to delete a row
from the Authors table, where au_name is Abraham
White by using the PreparedStatement object:

String str = "DELETE FROM Authors WHERE


au_name= ? ";

PreparedStatement ps = con.prepareStatement(str);
ps.setString(1, "Abraham White");
int rt=ps.executeUpdate();
Activity: Creating an Application that
Uses the PreparedStatement Object

Problem Statement
The management of City library has decided to
computerize the book inventory. The library
management has assigned the preceding task to
a leading software development company of the
US.
The Lead Analyst has assigned the development
of the Book Inventory application to Mark, the
Senior Software Developer.

However, in the initial phase, Mark has decided


to create an interface that will allow a user to
add the details of a new publisher to the
publishers table, as shown in the following
figure.
Prerequisite
You need to ensure that the Library database
exists and comprises the Publishers table.
The structure of the Publishers table should be
similar to the structure, as shown in the following
figure.
Exercise
The management of Park Library has decided to
automate the task of managing the author’s details in
a database. For this, the library management has
assigned the task to a leading software development
company of the US.

The Senior Software Developer has assigned the


development of the Author Management application to
Jessica, the Junior Software Developer.

For this application, Jessica needs to implement the


functionality to view, insert, update, and delete an
author’s information.

Help Jessica to achieve the preceding requirement.


Managing Database Transactions
A transaction is a set of one or more SQL
statements executed as a single unit. A
transaction is complete only when all the SQL
statements in a transaction execute
successfully.

If any one of the SQL statements in the


transaction fails, the entire transaction is rolled
back, thereby, maintaining the consistency of
the data in the database.
JDBC API provides the support for transaction
management.

For example,
a JDBC application is used to transfer money from
one bank account to another. This transaction
gets completed when the money is deducted from
the first account and added to the second.

If an error occurs while processing the SQL


statements, both the accounts remain unchanged.
The set of the SQL statements, which transfers
money from one account to another, represents a
transaction in the JDBC application.
The database transactions can be committed in the
following two ways in the JDBC applications:

Implicit: The Connection object uses the auto-commit


mode to execute the SQL statements implicitly. The
auto-commit mode specifies that each SQL statement in
a transaction is committed automatically as soon as the
execution of the SQL statement completes. By default,
all the transaction statements in a JDBC application are
auto-committed.

Explicit: For explicitly committing a transaction


statement in a JDBC application, you need to use the
setAutoCommit() method. This method accepts either of
the two values, true or false, to set or reset the auto-
commit mode for a database. The auto-commit mode is
set to false to commit a transaction explicitly. You can
set the auto-commit mode to false using the following
code snippet:
con.setAutoCommit(false);
In the preceding code snippet, con represents a
Connection object.
Committing a Transaction
When you set the auto-commit mode to false, the
operations performed by the SQL statements are
not reflected permanently in a database.

You need to explicitly call the commit() method of


the Connection interface to reflect the changes
made by the transactions in a database.

All the SQL statements that appear between the


setAutoCommit(false) method and the commit()
method are treated as a single transaction and
executed as a single unit.
The rollback() method is used to undo the
changes made in the database after the last
commit operation. You need to explicitly invoke
the rollback() method to revert a database in the
last committed state.

When the rollback() method is invoked, all the


pending transactions of a database are cancelled
and the database gets reverted to the state in
which it was committed previously.

You can call the rollback() method using the


following code snippet:

con.rollback();
In the preceding code snippet, con represents a
Connection object.
Live Demo
Implementing Batch Updates in JDBC

A batch is a group of update statements sent


to a database to be executed as a single unit.

You send the batch to a database in a single


request using the same Connection object. This
reduces network calls between the application
and the database.

Therefore, processing multiple SQL


statements in a batch is a more efficient way
as compared to processing a single SQL
statement.
The Statement interface provides
following methods to create and execute
a batch of SQL statements:

 void addBatch(String sql): Adds an SQL


statement to a batch.

 int[] executeBatch(): Sends a batch to a


database for processing and returns
the total number of rows updated.

 void clearBatch(): Removes the SQL


statements from the batch.
You can create a Statement object to perform
batch updates. When the Statement object is
created, an empty array gets associated with
the object. You can add multiple SQL
statements to the empty array for executing
them as a batch.

You also need to disable the auto-commit mode


using the setAutoCommit(false) method while
working with batch updates in JDBC.

This enables you to roll back the entire


transaction performed using a batch of
updates if any SQL statement in the batch
fails.
You can use the following code snippet to create a
batch of SQL statements:

con.setAutoCommit(false);
Statement stmt=con.createStatement();

stmt.addBatch("INSERT INTO Publishers (pub_id,


pub_name) VALUES (P001, 'Sage Publications')");

stmt.addBatch("INSERT INTO Product (pub_id,


pub_name) VALUES (P002, 'Prisidio Press')");

In the preceding code snippet, con is a Connection


object. The setAutoCommit() method is used to set
the auto-commit mode to false. The batch contains
two INSERT statements that are added to the batch
using the addBatch() method.
The SQL statements in a batch are processed in
the order in which the statements appear in a
batch. You can use the following code snippet to
execute a batch of SQL statements:

int[] updcount=stmt.executeBatch();

In the preceding code snippet, updcount is an


integer array that stores the values of the update
count returned by the executeBatch() method.

The update count is the total number of rows


affected when an SQL statement is processed.

The executeBatch() method returns the updated


count for each SQL statement in a batch, if it is
successfully processed.
Live Demo

You might also like