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

2 Best-JDBC Final

The JDBC API, found in the java.sql and javax.sql packages, facilitates database connectivity in Java applications by providing classes and interfaces for establishing connections, executing SQL statements, and handling results. Key components include DriverManager, Connection, Statement, and ResultSet, which enable loading drivers, creating connections, executing queries, and managing data retrieval. Additionally, PreparedStatement allows for efficient execution of SQL statements with runtime parameters, improving performance by reducing database load.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

2 Best-JDBC Final

The JDBC API, found in the java.sql and javax.sql packages, facilitates database connectivity in Java applications by providing classes and interfaces for establishing connections, executing SQL statements, and handling results. Key components include DriverManager, Connection, Statement, and ResultSet, which enable loading drivers, creating connections, executing queries, and managing data retrieval. Additionally, PreparedStatement allows for efficient execution of SQL statements with runtime parameters, improving performance by reducing database load.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 64

JDBC API

 The JDBC API classes and interfaces are available in the


java.sql and the javax.sql packages.

 The classes and interfaces perform a number of tasks,


such as establish and close a connection with a
database , send a request to a database , retrieve data
from a database , and update data in a database.

 The commonly used classes and interfaces in the JDBC


API are:

1
 DriverManager class : Loads the driver for the
database.

 Driver (interface / Class) : Represents a database


driver. All JDBC driver classes must implement the Driver
interface.

 Connection interface : Enables you to establish a


connection between a Java application and a database.

 Statement interface : Enables you to execute SQL


statements

 ResultSet interface: Represents the information


retrieved from a database.

2SQLException class: Provides information about the


 To query a database and display the result using Java
applications , you need to :

1. Load a driver
2. Connect to a database
3. Create and execute JDBC statements
4. Handle SQL exceptions

3
Loading a Driver
 The first step to develop a JDBC application is to load
and register the required driver using the driver
manager .

 You can load and register a driver :

1. Programmatically :

. Using the forName() method


. Using the registerDriver () method

2. Manually:
4 . By setting system property
Using the forName () Method
 The forName() method is available in the
java.lang.Class class.

 The forName() method loads the JDBC driver and


registers the driver with the driver manager.

 The syntax to load a JDBC driver to access a database


is :
Class.forName (“driver_name”);

 You can load the JDBC-ODBC Bridge driver using the


following method call:

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
5
Using the registerDriver () method
 You can create an instance of the Driver class to load a JDBC driver.

 The syntax to declare an instance of the Driver class is :


Driver d = new <driver-name>;

 You can use the following statement to crate an instance of the


Driver class:
Driver d = new sun.jdbc.odbc.JdbcOdbcDriver ();

 Once you have created the Driver object ,call the registerDriver ()
method to register it with the DriverManager.

 You can register the JDBC-ODBC Bridge driver using the following
method call to registerDriver () method:
DriverManager.registerDriver (d) ;

6
Setting System Property
 Driver can also be loaded by setting system property for JDBC
drivers.

 You add the driver name to the jdbc.drivers system property to load
a JDBC driver.

 You use the –D command line option to set the system property on
the command line.

 The command to set the system property is :


java –Djdbc.drivers=sun.jdbc.odbc.JdbcOdbcDriver
Demo

 In the preceding command , jdbc.drivers is the property name and


sun.jdbc.odbc.JdbcOdbcDriver is the value that you need to set
for the property.

7
 After you load a driver , you need to establish the connection with a
Connecting to a Database
 You create an object of the Connection interface to establish a
connection with a database.

 You can create multiple Connection objects in a Java applications to


access and retrieve data from multiple databases.

 The DriverManager class provides the getConnection () to


create a Connection object.

 The getConnection () is an overloaded method that has the


following 3 forms:
1. Connection getConnection(String url) :

2. Connection getConnection (String url , String


uname ,String pass)

8 3. Connection getConnection(String url , Properties


String url = “jdbc:odbc:MyDataSource” ;
Connection con = DriverManager.getConnection(url);

The syntax for the JDBC url that is passed as a parameter to the
getConnection() method is :
<protocol>:<subprotocol>:<subname>

1. Protocol name : Indicates the name of the protocol that is used


to access a database. In JDBC, the name of the access protocol is
always jdbc .

2. Sub-protocol name : Indicates the mechanism to retrieve data


from a database. For example, if you use the JDBC-ODBC Bridge to
access a database, then the name of the sub protocol is odbc .

3. Subname : Indiacates the Data Source Name (DSN) that contains


database information, such as the name of a database , location of
9the database server , user name , and password to access a
database server.
String url = “jdbc:odbc:MyDataSource”;
Connection con=
DriverManager.getConnection(url,”uname”,”pass”);

String url = “jdbc:odbc:MyDataSource”;

Properties p = new Properties();

p.setProperty(“user” , “Newuser”);
p.setProperty(“password”,”NewPassword”);

Connection con = DriverManager.getConnection(url ,


p);

After you create a connection ,you need to write JDBC


10
statements
Creating and Executing JDBC Statements
 You need to create a Statement object to send requests to and
retrieve results from a database.

 The Connection object provides the createStatement () method to


create a Statement object.

Statement stmt = con.createStatement();

11
The Statement interface contains the following methods to send
static statements to a database:

1. ResultSet executeQuery (String str) : Executes an SQL


statement and returns a single object of the type , ResultSet. The
executeQuery () should be used when you need to retrieve data
from a database table using the SELECT statement.
Statement stmt = con.createStatement ();
ResultSet rs = stmt.executeQuery(<SQL
statement >);

2. int executeUpdate(String str) : Executes the SQL statements


and returns the number of data rows that are affected after
processing the SQL statement. When you need to modify data in a
database table using the DML statements , INSERT, DELETE, and
UPDATE you can use the executeUpdate() .
Statement stmt = con.createStatement
();
int s = stmt.executeUpdate(<SQL statement >);
12
3. boolean execute (String str ) : Executes an SQL statement and
returns a boolean value. You can use this method when the type of
SQL statement passed as parameter is not known or when the
statement being executed returns a result set or an update count.
The execute () method returns true if the of the SQL statement is
an object of ResultSet and false if it is an update count.

Statement stmt = con.createStatement();


stmt.execute(<SQL statement>);

You can use the DML statements , INSERT , UPDATE and DELETE , in
Java applications to modify the data stored in the databasetables.

You can also use the DDL statements, CREATE, ALTER and DROP in
java applications to define or change the structure of database
objects.

13
Querying a Table

String str = “SELECT * from authors” ;

Statement stmt = con.createStatement ();

ResultSet rs = stmt.executeQuery(str);

String str = “SELECT * from authors WHERE city = ‘Pune’ ”


;

Statement stmt = con.createStatement ();

14 ResultSet rs = stmt.executeQuery(str);
Handling SQL Exceptions
 The java.sql package provides the SQLException class , which is
derived from the java.lang.Exception class.

 The SQLException is thrown by various methods in the JDBC API and


enables you to determine the reason of the errors that occur while
connecting a Java application to a database.

 You can catch the SQLException in a Java application using the try
and catch exception handling block.

 The methods in the SQLException class are :

1. int getErrorCode () : Returns the error code associated


with the
error occurred.
2. String getSQLState() : X/Open error code.
15
3. SQLException getNextException () : Returns the next
exceptions in the chain of
Try
{
String str = “DELETE FROM authors WHERE au_id = ‘123’ ” ;

Statement stmt = con.createStatement();

int count = stmt.executeUpdate (str) ;


}
catch (SQLException sqlexception)
{
System.out.println (“Display Error Code”) ;
System.out.println( “SQL Exception” + sqlexception.getErrorCode
()) ;
}

16
Result Sets
 When you execute a query to retrieve data from a table using a
java application , the output of the query is stored in a ResultSet
object in a tabular format.

 A ResultSet objects maintains a cursor that enables you to move


through the rows stored in a ResultSet object.

 By Default , the ResultSet object maintains a cursor that moves in


the forward direction only.

 As a result , it moves from the first row to the last row in the
ResultSet.

 You cannot update the default ResultSet object.

 The cursor in the ResultSet object initially points before the first
row
17
Type of Results Sets
 Read only : Allows you to only read the rows in a ResultSet object.

 Forward only : Allows you to move the result set cursor from first
row to
last row in forward direction only.

 Scrollable : Allows you to move the result set cursor forward or


backward through the result set.

 Updatable : Allows you to update the result set rows retrieved from
a database table.

You can specify the type of a ResultSet object using the


createStatement () of the Connection interface.

The createStatement() accepts ResultSet fields as parameters to


18
create different types of the ResultSet objects.
ResultSet fields
 TYPE_SCROLL_SENSITIVE : Specifies that the cursor of the
ResultSet object is scrollable and it reflects the changes in the data
made by the other users.
 TYPE_SCROLL_INSENSITIVE : Specifies that the cursor of the
ResultSet object is scrollable and it does not reflect changes in the
data made by the other users.
 TYPE_FORWARD_ONLY : Specifies that the cursor of the ResultSet
object moves in forward direction only from the first row to the last
row.

 CONCUR_READ_ONLY : Specifies the concurrency mode that does


not allow you to update the ResultSet object.
 CONCUR_UPDATABLE : specifies the concurrency mode that allows
you to update the ResultSet object.

 HOLD_CURSORS_OVER_COMMIT : Specifies that a ResultSet object


should not be closed after data is committed to the database.
19
CLOSE_CURSORS_AT_COMMIT : Specifies that a Result Set object
should be closed after data is committed to the database.
The createStatement() is an overloaded method that has 3
prototypes.

1. Statement createStatement () : Does not accept any


parameter. This method creates a default ResultSet object that
only allows forward scrolling.

2. Statement createStatement (int , int) : The first parameter


indicates the ResultSet type that determines whether or not , a
result set cursor can move backward. The second parameter
indicates the concurrency mode for the result set that determines
whether the data in result set can be updates . This method creates
a ResultSet object with the given type and concurrency.

3. Statement createStatement (int , int , int ) : In addition to he


ResultSet types and the concurrency mode , this method accepts a
third parameter. This parameter indicates whether or not, the
result set is closed after committing data to the database. This
method creates a ResultSet object with the given type ,
concurrency and state.
20
Methods of ResultSet

 boolean first () : Shifts the control of a result set cursor to


the first row of the result set.

 boolean isFirst() : Determines whether the result set cursors


points to the first row of the result set.

 boolean beforeFirst() : Shifts the control of a result set cursor


before the first row of the result set.

 boolean isBeforeFirst () : Determines whether the result set


cursor points before the first row of the
result set.

 boolean last() : Shifts the control of a result set cursor to the


last row of the result set.

 boolean isLast () : Determines whether the result set cursor


21 points to the last row of the result set.
 boolean afterLast() : Shifts the control of a result set cursor after the last

row of the result set.

 boolean isAfterLast () : Determines whether the result set cursor points

after the last row of the result set.

 boolean previous () : Shifts the control of a result set cursoe to the

previous row of the result set.

 boolean absolute (int i) : Shifts the control of a result set cursor to the

row number that you specify as a paramter.

 boolean relative (int i) : Shifts the control of a result set cursor , forward

or backward , relative to he row number that you


specify as a paramter .This method accepts either
a positive or a negative values as a paramter

22
Statement stmt =
con.createStatement

(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

ResultSet rs = stmt.executeQuery(“SELECT * FROM authors”)

if (rs.isBeforeFirst()== true)
System.out.println(“Result set cursor id before first row in result
set”);

if (rs.first() == true)
System.out.println(rs.getString(1) + “,” +
rs.getString(2)+”,”+rs.getString(3));

System.out.println(“using absolute() method”);


rs.absolute(4);
23int rowcount = rs.getRow() ;
 JDBC allows you to create an updatable result set that enables
you to modify the rows in the result set.
 The following methods used with updatable result set:

1 . void updateRow () : Updates a row of the current ResultSet


object and the underlying database tables.

2. void insertRow () : Inserts a row in the current ResultSet object


and underlying database table.

3. void deleteRow () : Deletes a row from the current ResultSet


object and underlying database table.

4. void updateString () : Updates the specified column with the


given string value.

5. void updateInt() : Updates the specified column with the given


int value.
24
Statement stmt =
con.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE ,
ResultSet.CONCUR_UPDATABLE);

ResultSet rs = stmt.executeQuery
(“SELECT au_id , city , state FROM authors WHERE au_id =
‘123’ ”) ;

rs.next () ;

rs.updateString(“state” , “MAHARASHTRA”) ;
rs.updateString(“city” , “Pune”);

25
PreparedStatement interface

 The PreparedStatement objects accepts the runtime parameters.

 The PreparedStatement interface is derived from the Statement


interface and is available in the java.sql package.

 The PreparedStatement objects are compiled and prepared only


once by JDBC.

 The future invocation of the PreparedStatement object does not


recompile the SQL statements.

 This helps in reducing the load on the database server and thus
improving the performance of the application .

26
 The PreparedStatement interface inherits the following methods
to execute SQL statement s from the Statement interface:

1. ResultSet executeQuery () : Executes a SELECT statement


and returns the result in a ResultSet
object.

2. int executeUpdate(): Executes an SQL statement, INSERT ,


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

3. boolean execute () : Executes an SQL statement and returns a


boolean value.

27
stat = con.prepareStatement(“SELECT * FROM authors WHERE au_id =
? ”) ;

The SQL statement can contain ‘ ? ‘ symbol as placeholder that can


be replaced by input parameters at runtime.

Before executing the SQL statements specified in the


PreparedStatement object , you must set the value of each ‘ ? ‘
parameter.

This is done by calling an appropriate setXXX () method , where XXX


is the data type of the parameter.

28 stat.setString (1, “123”);


 The PreparedStatement interface provides various methods to
set the value of the placeholders for the specific data types.

1. void setByte (int index , byte val) : Sets the java byte type
value for the parameter corresponding to index passed as a
parameter.

2. void setBytes (int index , byte[] val) : Sets the Java byte
type array for the parameter corresponding to index passed as
a parameter.

3. void setBoolean (int index , boolean val) : Sets the Java


boolean type value for the parameter corresponding to index
passed as a parameter.

4. void setDouble (int index, double val) : Sets the Java double
type value value for the parameter corresponding to the index
passed as a parameter.
29
5. void setInt (int index , int val) : Sets the Java int type value for
the parameter corresponding to index passed as a parameter.

6. void setLong(int index , long val) : Sets the Java long type
value for the parameter corresponding to index passed as a
parameter.

7. void setFloat (int index , float val) : Sets the Java float type
value for the parameter corresponding to index passed as a
parameter.

8. void setShort (int index , short val) : Sets the Java short type
value for the parameter corresponding to index passed as a
parameter.

9. void setString(int index , String val) : Sets the Java String


30type value for the parameter corresponding to index passed as a
parameter.
Retrieving Rows

String str = “SELECT * FROM titles WHERE au_id = ? ” ;

PreparedStatement ps = con.prepareStatement(str) ;

ps.setString(1 , “101”);

ResultSet rs = ps.executeQuery ();

31
Inserting Rows

String str =
“ INSERT INTO authors (au_id , au_fname , au_lname) VALUES
(? , ? , ? ) ” ;

PreparedStatement ps = con.prepareStatement(str);

ps.setString (1, “101”);

ps.setString (2, “ABC”);

ps.setString (3 , “XYZ”);

int rt = ps.executeUpdate() ;
32
Updating & Deleting Row

String str = “ UPDATE authors SET state = ? WHERE city = ? “ ;

PreparedStatement ps = con.prepareStatement(str);

ps.setString (1, “MH”);


ps.setString (2, “Pune”);
int rt = ps.executeUpdate() ;

String str = “ DELETE FROM authors WHERE au_fname = ? “ ;

PreparedStatement ps = con.prepareStatement(str);

ps.setString (1, “PPPP”);


int rt = ps.executeUpdate() ;
33
Transactions

 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 statement in a


trasaction execute successfully.

 If any one of the SQL statements in the transaction fails , the


entire transaction is rolled back thereby maintaining consistency of
the data in the database.

 JDBC API provides support for transaction management.

 E.g. : transfer of money from a bank account.

34
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.
The auto-commit mode specifies that each SQL statement in a
transaction is committed automatically as soon as the execution
of SQL statement completes.
By default all the transaction statement in a JDBC application are
auto-committed.

Explicit :
For explicitly committing transaction statement in a JDBC
application, you have 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
35 method call : con.setAutoCommit (false) ;
 When you set the auto-commit mode to false ,the operations
performed by the SQL statement 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 statement that appear between two commit() methods
are treated as a single transaction and are executed as a single unit.
 The rollback () method is used to undo the changes made in the
database after the last commit operations.

 You need to explicitly invoke the rollback () method to revert a


database in the last committed state.
 When a rollback () method is invoked , all the pending transactions of
a database are cancelled and the database reverts the state in which
it was committed previously.

36
 You can call the rollback () method using the following method call :
Batch Updates

 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 in a single request using the


same Connection object.

 This reduces network calls between the application and the


database .

 For this reason , processing the multiple SQL statements in a batch


is a more efficient way as compared to the processing of a single
SQL statement.

 A JDBC transaction can comprise of multiple batches.


37
Implementing Batch Updates in JDBC

 The SQL statements that are part of a batch are called the
batchable statements.

 The Statement or PreparedStatement interface provides


following methods to create and executes a batch of SQL
statements :

1. void addBatch () : Adds an SQL statement to a batch .

2. void executeBatch () : Sends a batch of SQL statements to a


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

3.38void clearBatch () : Removes the SQL statements from the


 You can create Statement object to perform batch updates.

 When a Statement object is created an empty array is associated


with the object.

 You can add multiple SQL statements 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.

 This enables you to rollback the entire transaction performed using


a batch update if any SQL statement in the batch fails.

39
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 statement in a batch are processed in the order in which


the statements appear in a batch.

int [] updcount = stat.executeBatch () ;

40
Exception-Handling in Batch Updates
 The batch update operations can throw two types of exceptions ,
SQLException and BatchUpdateException.

 The JDBC API methods, addBatch () or executeBatch () throw the


SQLException when problem occurs while accessing a database.

 The SQLException exception is thrown when you try to execute a


SELECT statement using the executeBatch () method.

 The BatchUpdateException class is derived from


SQLException class.

 The BatchUpdateException exception is thrown when the SQL


statement in the batch cannot be executed due to :

1. Presence of illegal arguments in the SQL statement.


41 2. Absence of the database table.
 The BatchUpdateException uses an array of the update count to
identify the SQL statement that throws the exception.

 The update count for all the SQL statement that are executed
successfully is stored in the array in the same order in which the
SQL statement appear in the batch.

 You can traverse the array of update count to determine the SQL
statement that is not executed successfully in a batch.

 The null value in an array of update count indicates that the SQL
statement in the batch failed to execute.

42
import java.sql.*;
public class BatchUpdate
{
public static void main (String arg [])
{
try
{
/ * Batch Update Code comes here */
} catch (BatchUpdateException bexp)
{
System.err.println (“SQL Exception :” +
bexp.getMessage ()) ;
System.err.println(“Update Counts”) ;
int [] count = bexp.getUPdateCounts();

for (int I = 0 ; i<=count.length ; i++ )


System.err.println(count[i]) ;
43
}
Stored Procedures
 The java.sql package provides the CallableStatement interface that
contains various methods to enable you to call database stored
procedures.

 The CallableStatement interface is derived form the


PreparedStatement interface.

44
Creating Stored Procedures
 You can use the executeUpdate () to execute the CREATE
PROCEDURE SQL statement.
 Stored procedures can be of two types , parameterized and non-
parameterized.
 Non – parameterized stored procedure in a JDBC application:

String str = “ CREATE PROCEDURE authors_info”


+ “AS”
+ “SELECT au_id , au_lname , au_fname”
+ ”FROM authors”
+ “WHERE city = ‘Pune’ ”
+ ”ORDER BY au_fname” ;

Statement stmt = con.createStatement () ;

45 int rt = stmt.executeUpdate (str);


 The Connection object con is used to send the CREATE PROCEDURE
SQL statement to a database.

 When you execute the code , the authors_info stored procedure is


created and stored in the database.

46
 You can use the following code snippet to create a parameterized
stored procedure.

String str = “ CREATE PROCEDURE authors_info_prmtz


@auth_id varchar(15) , @auth_fname varchar(20)
output ,
@auth_lname varchar(20) output , @auth_city
varchar(20)
output , @auth_state varchar(20) output ”
+ “AS”
+ “SELECT @auth_fname = au_fname , @auth_lname
=
au_lname , @auth_city = city , @auth_state = state ”
+ “ FROM authors ”
+ “ WHERE au_id = @auth_id ” ;

Statement stmt = con.createStatement () ;


47
int rt = stmt.executeUpdate (str);
 In the preceding code snippet , the authors_info_prmtz stored
procedure is created that accepts author id as parameter and retrieve
the corresponding author information form the database.
 The retrieved information is stored in the OUT parameter.
 A stored procedure can accepts one or multiple parameters.
 A parameter of a stored procedure can take any of these forms :

1. IN : Refers to the argument that you pass to a stored procedure.


2. OUT : Refers to the return value of a stored procedure.
3. 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

 When you use the stored procedures to perform database operations,


it reduces network traffic because instead of sending multiple SQL
statements to a database , a single stored procedure is executed.
48
Calling a Stored Procedure without Parameters

 The Connection interface provides the prepareCall() method that


is used to create the CallableStatement object .

 This object is used to a call a stored procedure of a database .

 The prepareCall () is an overloaded method that has the following 3


forms:

49
1. CallableStatement prepareCall (String str) : Creates a
CallableStatement object to call a stored procedure. The prepareCall
() accepts a string as a parameter that contains an SQL statement to
call a stored procedure. You can also specify the placeholders to
accept parameters in the SQL statement.

2. CallableStatement prepareCall(String str , int resSetType , int


resSetConc):
Creates a CallableStatement object that returns ResultSet object that
has the specified result set type and concurrency mode.
The method accepts following 3 parameter :
String object :Contains the SQL statement to call a stored procedure.
The SQL statement can contains one or more parameters.
ResultSet types : Specifies any of the 3 result set types ,
TYPE_FORWARD_ONLY , TYPE_SCROLL_INSENSITIVE or
TYPE_SCROLL_SENSITIVE.
ResultSet concurrency modes :Specifies either of these concurrency
modes , CONCUR_READ_ONLY or CONCUR_UPDATABLE ,
for
50 a result set
3. CallableStatement prepareCall (String str , int
resSetType , int resSetConcur , int resSetHoldability) :
Creates a CallableStatement object that returns a ResultSet object .
This ResultSet object has the specified result type, concurrency
mode, and constant to set the result set state.

51
The syntax to call a stored procedure without parameter is :
{ call <procedure_name> } ;

String str = “ {call authors_info}” ;


CallableStatement cs = con.prepareCall (str) ;

ResultSet rs = cs.executeQuery() ;

while(rs.next())
{
System.out.println(“Author ID :” + rs.getString(1) + “\t”);
System.out.println(“Author First Name :” + rs.getString(2) + “\
t”);
System.out.println(“Author Last Name :” + rs.getString(3) + “\
t”);
52}
Calling a Stored Procedure with Parameters

 The SQL escape syntax is used to call a stored procedure with


parameters.

 There are two forms of the SQL escape syntax, one that contains
result parameter and one that does not.

 If the SQL escape syntax contains a result parameter, the result


parameter is used to return a value from a stored procedure.

 The result parameter is an OUT parameter. Other parameters of


the SQL escape syntax can contain IN , OUT , or INOUT parameters.

53
 The syntax to call a stored procedure with parameter is :

{ call <procedure_name> (?)} ;

 You need to set the value of the IN parameters before the


CallableStatement object executed , otherwise the SQLException is
thrown while processing the stored procedure.

<CallableStatement_object>.setInt(<value>)

54
 If the stored procedure contains OUT and INOUT parameters, these
parameters should be registered with corresponding JDBC types
before a call to a stored procedures is precessed.

 The JDBC types determine the Java data types that are used in the get
methods while retrieving the values of the OUT and INOUT
parameters.

cs.registerOutParameter (1 . Java.sql.Types.STRING) ;
Accepts the position of the placeholder and a constant in the
java.sql.Types class as parameters.

cs.registerOutParameter (1, java.sql.Types.DECIMAL ,


3) ;

What for 3rd Parameter used for ?


55
import java.sql.*;
public class CallProc
{
public static void main(String arg [])
{
String id , fname , lname , address , city ;

try
{

String str = “ { call authors_info ( ? , ? , ? , ? , ? ) } ” ;


Class.forname (“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con =
DriverManager.getConnection(“jdbc:odbc:DSN”) ;
CallableStatement cs = con.prepareCall (str) ;

// pass IN parameter
56
cs.setString (1 , “123-456” ) ;
//Register OUT paramter
cs.registerOutParameter(2 , Types.VARCHAR);
cs.registerOutParameter(3 , Types.VARCHAR);
cs.registerOutParameter(4 , Types.VARCHAR);
cs.registerOutParameter(5 , Types.VARCHAR);

// process the Stored procedure


cs.execute () ;

fname = cs.getString(2) ;
lname = cs.getString(3) ;
address = cs.getString(4) ;
city = cs.getString(5) ;
----
-----
----

}
57
Using METADATA in JDBC
 Metadata is the information about data , such as structure and
properties of a table.

 Employee table that has the name , address , salary , designation


and department columns.

 The metadata of the employee table includes information , such as


names of the columns , data type of each column and constraints
to enter data values in the table columns.

 The JDBC API provides the following 2 metadata interfaces to


retrieve the information about the database and result set :

1 . DatabaseMetaData interface
2 . ResultSetMetaData interface

58
DatabaseMetaData Interface
 The DatabaseMetaData interface provides the methods that enable
you to determine the properties of a database or RDBMS.

 These properties include names of database tables , database


version , SQL keywords , etc…. .

 You can create an object of DatabaseMetaData using the


getMetaData () of the Connection interface.

DatabaseMetaData dm = con.getMetaData () ;

 The following lists the commonly used methods of the


DatabaseMetaData interface :

59
 ResultSet getColumns (String catalog , String schema, String
tablename
String col_name)
-> Retrieves the information about a column of a database
table
that is available in the specified database 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 .

60String getDriverVersion ()
 ResultSet getPrimaryKeys (String catalog , String schema , String table)
-> Retrieves the information about the 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
61
supports savepoints.
Using ResultMetaData Interface

 The ResultSetMetaData interface contains various methods that


enable you to retrieve information about the data in a result set ,
such as number of columns , names of columns and data types of
the columns.

 The ResultSet interface provides the getMetaData () method to


create an object of the ResultSetMetaData interface .
ResultSetMetaData rm = rs.getMetaData() ;

 The following lists the commonly used methods of the


ResultSetMetaData interface :

62
 int getColumnCount () : Returns an integer indicating the total number
of
columns in a ResultSet object .

 String getColumnLabel (int col_index) : Retrieves the title of the


table column corresponding to the index passed as a parameter to this
method.

 String getColumnName (int col_index) : Retrieves the name of the


table column corresponding to the index passed as a parameter to this
method.

 int getColumnType (int col_index) : Retrieves the SQL data type of the
table column corresponding to the index passed as a parameter.

 String getTableName(int col_index) : Retrieves the name of the


63
database table that contains the column corresponding to the index
 boolean isAutoIncrement (int col_index) : Returns a boolean
value that indicates whether the table column corresponding to
the index passed as a parameter increments automatically.

 boolean isCaseSensitive (int col_index) : Returns a boolean


value that indicates whether the table column corresponding to the
index passed as a parameter is case sensitive.

 boolean isReadOnly (int col_index) : Returns a boolean value


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

 boolean isWritable (int col_index) : Returns a boolean value


that indicates whether ResultSet column corresponding to the
index passed as a parameter is updatable.
64

You might also like