Вы находитесь на странице: 1из 39

Creating Applications Using Advanced Features Of

JDBC
© 2007 ArisGlobal
Objectives

– In this section, you will learn about:

• Creating applications using the PreparedStatement object


• Managing database transactions
• Performing batch updates
• Creating and calling stored procedures in JDBC
• Using metadata in JDBC
Querying and Modifying Data Using the
PreparedStatement Object

– 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.
• Is compiled and prepared only once by JDBC. The future
invocation 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.
Querying and Modifying Data Using the
PreparedStatement Object (Contd.)

– Methods of the PreparedStatement Interface


• The PreparedStatement interface inherits the following methods
to execute SQL statements from the Statement interface:
– ResultSet executeQuery(): Executes a SELECT statements and
returns the result in a ResultSet object.
– int executeUpdate(): Executes an SQL statement, INSERT, UPDATE,
or DELETE and returns the count of the rows affected.
– boolean execute(): Executes an SQL statement and returns a boolean
value.
Querying and Modifying Data Using the
PreparedStatement Object (Contd.)

• 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 = ?");
• 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,"1001");
ResultSet result=stat.executeQuery();
Querying and Modifying Data Using the
PreparedStatement Object (Contd.)

– Retrieving Rows
• The code snippet to retrieve books written by an author from the titles
table using the PreparedStatement object is:
String str = "SELECT * FROM titles WHERE au_id = ?";
PreparedStatement ps= con.prepareStatement(str);
ps.setString(1, "1001");
ResultSet rs=ps.executeQuery();
– Inserting Rows
• The code snippet to create a PreparedStatement object that inserts a row
into authors table by passing authors data at runtime is:
String str = "INSERT INTO authors (au_id, au_fname, au_lname) VALUES
(?, ?, ?)";
PreparedStatement ps = con.prepareStatement(str);
ps.setString(1, "1001");
ps.setString(2, "Abraham");
ps.setString(3, "White");
int rt=ps.executeUpdate();
Querying and Modifying Data Using the
PreparedStatement Object (Contd.)
– Updating and Deleting Rows
• The code snippet to modify the state to CA where city is Oakland
in the authors table using the PreparedStatement 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();
– The code snippet to delete a row from the authors table
where author’s first name is Abraham using the
PreparedStatement object is:
String str = "DELETE FROM authors WHERE au_fname= ? ";
PreparedStatement ps = con.prepareStatement(str);
ps.setString(1, "Abraham");
int rt=ps.executeUpdate();
Demonstration- Creating an Application that
Uses PreparedStatement Object
Example
import java.sql.*;
import java.util.*;
class Prepare {
public static void main(String args[]) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver"); Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@CHARULB:
1521:orcl","user1","user1");
Statement stmt = con.createStatement();
PreparedStatement ps=con.prepareStatement("UPDATE emp SET
empName =? WHERE empID =? ");
Example

Continued…
ps.setString(1, "Tom");
ps.setInt(2,3);
ps.executeUpdate();
ResultSet rs = stmt.executeQuery("SELECT * FROM emp");
while(rs.next()){
String s=rs.getString("empName");
int n=rs.getInt("empID");
System.out.println("Employee Name = " + s);
System.out.println("Employee Id = " + n);
} con.close();
Example

Continued…
//Here 1 and 2 are the sequential number of values to be
set.
}catch(Exception ex){
System.out.println(ex);

System.exit(0);

}
Managing Database Transactions
– 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.
Managing Database Transactions
(Contd.)

New D/B
On Commit
SQL Query
Database to update the
table

Old D/B
On Rollback
Managing Database Transactions
(Contd.)

– 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);
– Committing a Transaction
• 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.
Isolation Levels
– The transaction isolation levels in JDBC determine whether
the concurrently running transactions in a database can affect
each other or not.
– Some common problems that might occur when multiple
transactions simultaneously access a database are:
• Dirty reads:
one transaction can change a value, and a second transaction can read
this value before the original change has been committed or rolled back.
• Non-repeatable reads:
when a transaction reads the same row more than one time, and between
the two (or more) reads, a separate transaction modifies that row.
Because the row was modified between reads within the same transaction,
each read produces different values, which introduces inconsistency.
• Phantom reads:
Phantom behavior occurs when a transaction attempts to select a row that
does not exist and a second transaction inserts the row before the first
transaction finishes. If the row is inserted, the row appears as a phantom
to the first transaction, inconsistently appearing and disappearing.
Isolation Levels (Contd.)

– The isolation levels enable you to isolate the concurrently


running transactions so that a transaction cannot affect the
result of another transaction.
– The Connection interface of the JDBC API provides the
following fields as int values to set isolation levels:
• TRANSACTION_READ_UNCOMMITTED
A constant indicating that dirty reads, non-repeatable reads and
phantom reads can occur.
• TRANSACTION_READ_COMMITTED
A constant indicating that dirty reads are prevented; non-repeatable
reads and phantom reads can occur.
• TRANSACTION_REPEATABLE_READ
A constant indicating that dirty reads and non-repeatable reads are
prevented; phantom reads can occur.
• TRANSACTION_SERIALIZABLE
A constant indicating that dirty reads, non-repeatable reads and
phantom reads are prevented.
Isolation Levels (Contd.)

– The Connection interface contains the following methods to retrieve


and set the value of transaction isolation level for a database:
• getTransactionIsolationLevel()
• setTransactionIsolationLevel()
– The code snippet to use the getTransactionIsolationLevel() method is:
Connection con = DriverManager.getConnection
("jdbc:odbc:MyDatasource","administrator","");
int transLevel=getTransactionIsolationLevel();

– The code snippet to use the setTransactionIsolationLevel() method is


Connection con = DriverManager.getConnection
("jdbc:odbc:MyDatasource","administrator","");
int transLevel=getTransactionIsolationLevel();
con.setTransactionIsolationLevel(TRANSACTION_SERIALIZABLE);
Performing Batch Updates

– 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.
Performing Batch Updates (Contd..)
– Implementing Batch Updates in JDBC
• The Statement or PreparedStatement 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 to a database
for processing and returns the total number of the rows updated.
– void clearBatch(): Removes the SQL statements from the batch.

• When a Statement object is created to perform batch updates, an


empty array is associated with the object.
• Multiple SQL statements can be added to the empty array to
execute them as a batch.
• You also need to disable the auto-commit mode using
setAutoCommit(false) while working with batch updates in JDBC.
• The executeBatch() method returns an integer array that stores
the values of the update count.
• The update count is the total number of rows affected when an
SQL statement in a batch is processed.
Performing Batch Updates (Contd..)

• The code snippet to create a batch of SQL statements is:


– con.setAutoCommit(false);
– Statement stmt=con.createStatement();
stmt.addBatch("INSERT INTO product (p_id, p_desc) VALUES
(1001, 'Printer')");
stmt.addBatch("INSERT INTO product (p_id, p_desc) VALUES
(1002, 'Scanner')");

• The SQL statements in a batch are processed in the order in


which the statements appear in a batch.

• The method call to execute a batch of SQL statements is:


int[] updcount=state.executeBatch();
Performing Batch Updates (Contd.)

– Exception Handling in Batch Updates


• The batch update operations can throw two types of exceptions:
– SQLException
– BatchUpdateException
• The BatchUpdateException class is derived from SQLException
class.
• The the SQLException is thrown by the JDBC API methods,
addBatch() or executeBatch(), 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 the exception.
Creating and Calling Stored Procedures in
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 the
PreparedStatement interface.
– Creating Stored Procedure
• Stored Procedures:
– Can be created using the CREATE PROCEDURE SQL statement in
JDBC applications.
– Are of two types:
» Parameterized
» Non-parameterized
Creating and Calling Stored Procedures in
JDBC (Contd.)

– 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 stored procedure.
• 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 and Calling Stored Procedures in
JDBC (Contd.)
– Calling a Stored Procedure without Parameters
• 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 <procedure_name> };
Creating and Calling Stored Procedures in
JDBC (Contd.)

– Calling a Stored Procedure with Parameters


• The SQL escape syntax is a standard way to call a stored
procedure from a Relational Database Management System
(RDBMS) and is independent of the RDBMS.
• There are two forms of the SQL escape syntax, one that contains
result parameter and one that does not.
• The syntax of the SQL escape syntax is:
{[? =] call <procedure_name> [<parameter1>,<parameter2>,
..., <parameterN>]}
• 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 <procedure_name>(?) };
• 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:
– <CallableStatement_object>.setInt(<value>);
Creating and Calling Stored Procedures in
JDBC (Contd.)

– 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)
Using Metadata in 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 interface
• ResultSetMetaData interface
Using Metadata in JDBC (Contd.)

– Using DatabaseMetaData Interface


• The DatabaseMetaData interface provides the methods that
enable you to determine the properties of a database or RDBMS.
• An object of DatabaseMetaData is created using the
getMetaData() method of the Connection interface.
• The method call to create an object of the DatabaseMetaData
interface is:
– DatabaseMetaData dm=con.getMetaData();
Using Metadata in JDBC (Contd.)

– The following table lists the commonly used methods of the


DatabaseMetaData interface:

Method Description

ResultSet getColumns(String catalog, Retrieves the information about a


String schema, String table_name, column of a database table that is
String column_name) available in the specified catalog.

Connection getConnection() Retrieves the database connection that


creates the DatabaseMetaData object.

String getDriverName() Retrieves the name of the JDBC driver


for the DatabaseMetaData object.

String getDriverVersion() Retrieves the version of the JDBC driver.


Using Metadata in JDBC (Contd.)

– The methods of the DatabaseMetaData interface: (Contd.)

Method Description

ResultSet getPrimaryKeys(String Retrieves the information about the


catalog, String schema, String table) primary keys of the database tables.

String getURL() Retrieves the URL of the database.

boolean isReadOnly() Returns a boolean value that indicates


whether the database is a read only
database.

boolean supportsSavepoints() Returns a boolean value that indicates


whether the database supports
savepoints.
Using Metadata in JDBC (Contd.)

– Using the ReultSetMetaData Interface

• 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 ResultSetMetaData interface.
• The method call to create an object of the ResultSetMetaData
interface:
ResultSetMetaData rm=rs.getMetaData();
Using Metadata in JDBC (Contd.)

• The following table lists the commonly used methods of the


ResultSetMetaData interface:

Method Description

int getColumnCount() Returns an integer indicating the total number of


columns in a ResultSet object.

String getColumnLabel(int Retrieves the title of the table column corresponding


column_index) to the index passed as a parameter to this method.

String getColumnName(int Retrieves the name of the table column corresponding


column_index) to the index passed as a parameter to this method.

int getColumnType(int Retrieves the SQL data type of the table column
column_index) corresponding to the index passed as a parameter.
Using Metadata in JDBC (Contd.)

• The methods of the ResultSetMetaData interface: (Contd.)

Method Description

String getTableName(int Retrieves the name of the database table that


column_index) contains the column corresponding to the index
passed as a parameter.

boolean Returns a boolean value that indicates whether the


isAutoIncrement(int table column corresponding to the index passed as a
column_index) parameter increments automatically.

boolean Returns a boolean value that indicates whether the


isCaseSensitive(int table column corresponding to the index passed as a
column_index) parameter is case sensitive.
Using Metadata in JDBC (Contd.)

• The methods of the ResultSetMetaData interface: (Contd.)

Method Description

boolean isReadOnly(int Returns a boolean value that indicates


column_index) whether the column in a ResultSet
corresponding to the index passed as a
parameter is read only.

boolean isWritable(int Returns a boolean value that indicates


column_index) whether ResultSet column corresponding
to the index passed as a parameter is
updatable.
Demonstration- Creating an Application to
Retrieve the Information of Database Tables
import java.sql.*;
import java.util.*;

class ConnectMeta {
public static void main(String args[]) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");

Connection
connection=DriverManager.getConnection("jdbc:oracle:thi
n:@CHARULB:1521:orcl","user1","user1");
DatabaseMetaData meta=connection.getMetaData();
Example

Continued…
System.out.print("Database : "+meta.getDatabaseProductName());
System.out.println("Database Product Version
:"+meta.getDatabaseProductVersion());
System.out.println("Driver name : "+meta.getDriverName());
System.out.println("Driver version : "+meta.getDriverVersion());
System.out.println("Max Column Length :
"+meta.getMaxColumnNameLength());
System.out.println("Max Row Size : "+meta.getMaxRowSize());
connection.close();
}catch(Exception ex){
System.out.println(ex);
System.exit(0);
}
}
}
Summary

– In this lesson, you learned:


– The PreparedStatement object of the Connection interface 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 successfully executed.
– If the setAutoCommit() method is set to true the database operations
performed by the SQL statements are automatically committed in the
database.
Summary (Contd.)

– 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 same Connection object.
– The executeBatch() method returns an integer array that stores the
update count for all the SQL statements that are executed
successfully in a batch. The update count is the number of database
rows affected by the database operation performed by each SQL
statement.
– Batch update operations can throw two types of exceptions,
SQLException and BatchUpdateException.
– The SQLException is thrown when the database access problem
occurs. The SQLException is also thrown when a SELECT statement
that returns a ResultSet object is executed in a batch.
Summary (Contd.)

– 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.
– The parameters of a stored procedure can take any of these three
forms:
• IN: Refers to the argument that you pass to a stored procedure.
• OUT: Refers to the return value of a stored procedure.
• INOUT: Enables you pass an argument to a stored procedure. The
same parameters can also be used to pass a return value of a
stored procedure.
– 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.)

– The DatabaseMetaData interface declares methods that enable you to


determine the properties of a database or RDBMS.
– The ResultSetMetaData interface declares methods that enable you to
determine information about data in a result set.
– The getMetaData() method of the Connection interface enables you to
declare the objects of the DatabaseMetaData interface. The methods
in the DatabaseMetaData interface retrieve information only about the
database to which a Java application is connected.
– The getMetaData() method of the ResultSet interface enables you to
create the instance of the ResultSetMetaData interface.

Вам также может понравиться