Upload
smita-r-s
View
216
Download
0
Embed Size (px)
Citation preview
7/28/2019 13-JDBC_59
1/59
JDBC BasicsJDBC Basics
Welcome to JDBC Basics presentation.
2/21/2006
7/28/2019 13-JDBC_59
2/59
1
2
Agenda
What is JDBC?
Step By Step Usage of JDBC API
DataSource & Connection Pooling
Transaction
Prepared and Callable Statements
2/21/2006
7/28/2019 13-JDBC_59
3/59
What is JDBC?What is JDBC?
2/21/2006
7/28/2019 13-JDBC_59
4/59
1
4
What is JDBC?
Standard Java API for accessingrelational database Hides database specific details from
application
Part of Java SE (J2SE)
Java SE 6 has JDBC 4
2/21/2006
7/28/2019 13-JDBC_59
5/59
1
5
JDBC API
? Defines a set of Java Interfaces, which are
implemented by vendor-specific JDBC Drivers Applications use this set of Java interfaces for
performing database operations - portability
? Majority of JDBC API is located injava.sqlpackage
DriverManager, Connection, ResultSet,DatabaseMetaData, ResultSetMetaData,PreparedStatement, CallableStatement and Types
? Other advanced functionality exists in thejavax.sql package
DataSource
JDBC API is a set of Java interfaces, which are implemented by vendor
specific JDBC drivers. Since applications use JDBC Java interfaces for
performing database operations, they don't have to be tied up with a
particular implementation, thus achieving portability regardless of what
database server they are using.
The majority of JDBC API is located in java.sql.* package. And other
advanced functionality such as DataSource is located in javax.sql package.
2/21/2006
7/28/2019 13-JDBC_59
6/59
1
6
JDBC Driver
? Database specific implemention ofJDBC interfaces Every database server has corresponding
JDBC driver(s)
? You can see the list of available driversfrom
http://industry.java.sun.com/products/jdbc/drivers
The JDBC driver is a database specific implementation of theJDBC interfaces. So every database server, whether it is Derby orOracle or MySQL, has its own JDBC driver.
2/21/2006
7/28/2019 13-JDBC_59
7/59
1
7
Database URL
? Used to make a connection to the database
Can contain server, port, protocol etc
? jdbc:subprotocol_name:driver_dependant_databasename
Oracle thin driver
jdbc:oracle:thin:@machinename:1521:dbname
Derby
jdbc:derby://localhost:1527/sample
Pointbase
jdbc:pointbase:server://localhost/sample
The Database URL is database vendor specific and is used formaking a connection to a particular database server. The syntaxtypically contains server, port, protocol information. So whendeveloping for a specific database, such as Oracle, Derby, orPointbase, you should review their documentation for the exactusage.
2/21/2006
7/28/2019 13-JDBC_59
8/59
Step By Step Usageof JDBC API
2/21/2006
7/28/2019 13-JDBC_59
9/59
1
9
Steps of Using JDBC
1.Load DB-specific JDBC driver
2.Get a Connection object
3.Get a Statement object
4.Execute queries and/or updates
5.Read results
6.Read Meta-data (optional step)
7.Close Statement and Connectionobjects
2/21/2006
7/28/2019 13-JDBC_59
10/59
1
10
1. Load DB-Specific DatabaseDriver
? To manually load the database driver andregister it with the DriverManager, load itsclass file Class.forName()
try {
// This loads an instance of the Pointbase DB Driver.
// The driver has to be in the classpath.
Class.forName("org.apache.derby.jdbc.ClientDriver");
}catch (ClassNotFoundException cnfe){
System.out.println("" + cnfe);
}
.
2/21/2006
7/28/2019 13-JDBC_59
11/59
1
11
2. Get a Connection Object? DriverManagerclass is responsible for selecting
the database and and creating the databaseconnection
Using DataSource is a prefered means ofgetting a conection object (we will talk aboutthis later)
? Create the database connection as follows:
try {
Connection connection =DriverManager.getConnection("jdbc:derby://localhost:1527/sample", app"," app ");
} catch(SQLException sqle) {
System.out.println("" + sqle);
}
This is just a quick example. In real world usage, you obviously declare the
connection variable outside of the try/catch block
2/21/2006
7/28/2019 13-JDBC_59
12/59
1
12
DriverManager & Connection
? java.sql.DriverManager getConnection(String url, String user, String password)
throws SQLException
? java.sql.Connection Statement createStatement() throws SQLException
void close() throws SQLException
void setAutoCommit(boolean b) throws SQLException
void commit() throws SQLException
void rollback() throws SQLException
This is a quick view of the DriverManager and Connection APIs.These are just a few of the methods for each class.
If you want to see them all, just review the javadoc
2/21/2006
7/28/2019 13-JDBC_59
13/59
1
13
3. Get a Statement Object
? Create a StatementObject fromConnection object
java.sql.StatementResultSet executeQuery(string sql)
int executeUpdate(String sql)
Example:Statement statement = connection.createStatement();
? The same Statement object can beused for many, unrelated queries
Once you have the Connection object, you can then execute SQLstatements against the database. The Statement Object isresponsible for sending the SQL commands to the database and forretrieving the results of that command.
The same Statement object can be used in multiple queries. Youjust have to call the necessary method with the appropriate SQLstring
2/21/2006
7/28/2019 13-JDBC_59
14/59
1
14
4. Executing Query or Update
? From the Statement object, the 2 most usedcommands are (a) QUERY (SELECT)
ResultSet rs = statement.executeQuery("select * fromcustomer_tbl");
(b) ACTION COMMAND (UPDATE/DELETE) int iReturnValue = statement.executeUpdate("update
manufacture_tbl set name = IBM' where mfr_num =19985678");
Here are the 2 most used SQL Commands. A Select and anUpdate/Insert
The main different between these to commands is that the QUERYcommand returns a ResultSet object while the ACTIONCOMMAND returns an int value. The ResultSet contains thevalues of your query while the int is the total number of recordsaffected by your statement.
2/21/2006
7/28/2019 13-JDBC_59
15/59
1
15
5. Reading Results
? Loop through ResultSet retrievinginformation java.sql.ResultSet
? boolean next()
? xxx getXxx(int columnNumber)
? xxx getXxx(String columnName)
? void close()
? The iterator is initialized to a position beforethe first row
You must call next()once to move it to the first row
The executeQuery() object returns a ResultSet object which is a 2dimensional array that contains the results of the executed SQLstatement. The developer has to loop through this object andretrieve each column and row. Unless the ResultSet is a scrollableResultSet (advanced topics), once you read through the ResultSetonce, you can no longer make use of it. In most cases, thedeveloper loops through the ResultSet and stores the values in
Collection so that the data can be used at a later date.A scrollable ResultSet is a ResultSet in which you can loopforward and backwards until the ResultSet object is closed. Ihavent had much experience with Scrollable ResultSets becausethey are Vendor specific as to who supports them and theimplementation is not all that reliable in my experience. If you areinterested in loop through the data more then once, or going to anyspecify row/column at any point in time, you might want toconsider converting the resultset to a Collection such as ArrayListor Vector. Once you have created the Collection Object, you are
free to manipulate the data in any manner availble through thoseobjects
2/21/2006
7/28/2019 13-JDBC_59
16/59
1
16
5. Reading Results (Continued)
? Once you have the ResultSet, you can easilyretrieve the data by looping through it
while (rs.next()){
// Wrong this will generate an error
String value0 = rs.getString(0);
// Correct!
String value1 = rs.getString(1);
int value2 = rs.getInt(2);
int value3 = rs.getInt(ADDR_LN1");
}
Unlike Arrays, the index for a ResultSet starts at 1, not 0.
You can specify either the column name or the column number
2/21/2006
7/28/2019 13-JDBC_59
17/59
1
17
5. Reading Results (Continued)
? When retrieving data from theResultSet, use the appropriategetXXX() method
getString()
getInt()
getDouble()
getObject()
? There is an appropriate getXXX methodof eachjava.sql.Types datatype
These are just a few of the many choices. Check thejava.sql.ResultSet API for a full listing of the accessor methods
Note: you can use getString() on any column type and it will makethe conversion for you.
2/21/2006
7/28/2019 13-JDBC_59
18/59
1
18
6. Read ResultSet MetaData andDatabaseMetaData (Optional)
? Once you have the ResultSet orConnection objects, you can obtain theMeta Data about the database or thequery
? This gives valuable information about thedata that you are retrieving or thedatabase that you are using ResultSetMetaData rsMeta = rs.getMetaData();
DatabaseMetaData dbmetadata =connection.getMetaData();
There are approximately 150 methods in theDatabaseMetaData class.
Both the ResultSetMetaData and the DatabaseMetaData provide extremely useful
information to a developer about the ResultSet they have and the database that they
are using.
2/21/2006
7/28/2019 13-JDBC_59
19/59
1
19
ResultSetMetaData Example
ResultSetMetaData meta = rs.getMetaData();//Return the column count
int iColumnCount = meta.getColumnCount();
for (int i =1 ; i
7/28/2019 13-JDBC_59
20/59
DataSource &Connection Pooling
2/21/2006
7/28/2019 13-JDBC_59
21/59
1
21
Sub-Topics
? DataSource interface and DataSourceobject
? Properties of a DataSource object
? JNDI registration of a DataSourceobject
? DataSource object that implementsConnection pooling
? Retrieval of DataSource object (withinyour application)
.
2/21/2006
7/28/2019 13-JDBC_59
22/59
1
22
javax.sql.DataSource Interfaceand DataSource Object
? Driver vendor implements the interface
? DataSource object is the factory for creatingdatabase connections
In the JDBC API, databases are accessed via DataSource objects. A DataSourcehas a set of properties that identify and describe the real world data source that it
represents. These properties include information such as the location of thedatabase server, the name of the database, the network protocol to use to
communicate with the server, and so on. In the Application Server, a data sourceis called a JDBC resource.
2/21/2006
7/28/2019 13-JDBC_59
23/59
1
23
javax.sql.DataSource Interfaceand DataSource Object
?
Three types of possible implementations Basic implementation: produces standard
Connection object
Connection pooling implementation: produces aConnection object that will automatically participatein connection pooling
Distributed transaction implementation: produces aConnection object that may be used for distributedtransactions and almost always participates inconnection pooling
.
2/21/2006
7/28/2019 13-JDBC_59
24/59
1
24
Properties of DataSource Object? A DataSource object has properties that can be
modified when necessary these are defined ina container's configuration file
location of the database server
name of the database
network protocol to use to communicatewith the server
? The benefit is that because the data source'sproperties can be changed, any code accessingthat data source does not need to be changed
? In the Sun Java System Application Server, a
data source is called a JDBC resource
.
2/21/2006
7/28/2019 13-JDBC_59
25/59
1
25
Where Are Properties of aDataSource Defined?
?
In container's configuration file? In Sun Java System App Server, they are
defined in /domains/domain1/config/domain.
xml
? In Tomcat, they are defined in server.xml /conf/server.xml
To store, organize, and retrieve data, most applications use a relational database.J2EE components access relational databases through the JDBC API. For
information on this API, see:
http://java.sun.com/docs/books/tutorial/jdbc
In the JDBC API, databases are accessed via DataSource objects. A DataSourcehas a set of properties that identify and describe the real world data source that it
represents. These properties include information such as the location of thedatabase server, the name of the database, the network protocol to use to
communicate with the server, and so on. In the Application Server, a data sourceis called a JDBC resource.
2/21/2006
7/28/2019 13-JDBC_59
26/59
1
26
DataSource (JDBC Resource) Definition inSun Java System App Server's domain.xml
7/28/2019 13-JDBC_59
27/59
1
27
DataSource Definition in SunJava System App Server
This is a Tomcat specific example using the DBCP (Database Connection Pooling)
package from Jakarta connecting to an Oracle Database
This entry can go into a couple of different place in your server.xml
Accessible to only your application
Accessible by all applications
2/21/2006
7/28/2019 13-JDBC_59
28/59
1
28
DataSource Definition in SunJava System App Server
.
2/21/2006
7/28/2019 13-JDBC_59
29/59
1
29
JNDI Registration of aDataSource Object
?
A driver that is accessed via a DataSourceobject does not register itself with theDriverManager
? Rather, a DataSource object is registered toJNDI naming service by the container andthen retrieved by a client though a lookupoperation
? With a basic implementation, the connectionobtained through a DataSource object isidentical to a connection obtained through
the DriverManager facility
.
2/21/2006
7/28/2019 13-JDBC_59
30/59
1
30
JNDI Registration of a DataSource(JDBC Resource) Object
?
The JNDI name of a JDBC resource isexpected in thejava:comp/env/jdbcsubcontext
For example, the JNDI name for the resource ofa BookDB database could be
java:comp/env/jdbc/BookDB
? Because all resource JNDI names are in thejava:comp/env subcontext, when youspecify the JNDI name of a JDBC resourceenter only jdbc/name. For example, for a
payroll database, specifyjdbc/BookDB
.
2/21/2006
7/28/2019 13-JDBC_59
31/59
1
31
Why Connection Pooling?
? Database connection is an expensive
and limited resource Using connection pooling, a smaller number
of connections are shared by a larger numberof clients
? Creating and destroying databaseconnections are expensive operations Using connection pooling, a set of
connections are pre-created and areavailable as needed basis cutting down onthe overhead of creating and destroyingdatabase connections
.
2/21/2006
7/28/2019 13-JDBC_59
32/59
1
32
Connection Pooling &DataSource
? DataSource objects that implementconnection pooling also produce aconnection to the particular data sourcethat the DataSource class represents
? The connection object that thegetConnection method returns is ahandle to a PooledConnection objectrather than being a physical connection The application code works the same way
2/21/2006
7/28/2019 13-JDBC_59
33/59
1
33
Example: PointBasePool
? The Sun Java Application Server isdistributed with a connection poolnamed PointBasePool, which handlesconnections to the PointBase databaseserver
? Under Sun Java Application Server,each DataSource object is associatedwith a connection pool
2/21/2006
7/28/2019 13-JDBC_59
34/59
1
34
Retrieval and Usage of aDataSource Object?
Application perform JNDI lookup operationto retrieve DataSource object
? DataSource object is then used to retrieve aConnection object
? In the application's web.xml, information onexternal resource, DataSource object in thiscase, is provided
? For Sun Java System App server, themapping of external resource and JNDIname is provided
This provides further flexibility
To store, organize, and retrieve data, most applications use a relational database.J2EE components access relational databases through the JDBC API. For
information on this API, see:
http://java.sun.com/docs/books/tutorial/jdbc
In the JDBC API, databases are accessed via DataSource objects. A DataSourcehas a set of properties that identify and describe the real world data source that it
represents. These properties include information such as the location of thedatabase server, the name of the database, the network protocol to use to
communicate with the server, and so on. In the Application Server, a data sourceis called a JDBC resource.
2/21/2006
7/28/2019 13-JDBC_59
35/59
1
35
Example: Retrieval ofDataSource Object via JNDI
? BookDBAO.java in bookstore1 application
public class BookDBAO {private ArrayList books;Connection con;private boolean conFree = true;
public BookDBAO() throws Exception {try {
Context initCtx = new InitialContext();Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)envCtx.lookup("jdbc/BookDB");
con = ds.getConnection();} catch (Exception ex) {
throw new Exception("Couldn't open connection to database: " +
ex.getMessage());}
2/21/2006
7/28/2019 13-JDBC_59
36/59
1
36
JNDI Resource Information inbookstore1's web.xml
jdbc/BookDB
javax.sql.DataSource
Container
Shareable
.
2/21/2006
7/28/2019 13-JDBC_59
37/59
1
37
JNDI and Resource Mapping inbookstore1's sun-web.xml
/bookstore1
jdbc/BookDB
jdbc/BookDB
.
2/21/2006
7/28/2019 13-JDBC_59
38/59
TransactionTransaction
2/21/2006
7/28/2019 13-JDBC_59
39/59
1
39
Transaction
? One of the main benefits to using aPreparedStatement is executing thestatements in a transactional manner
? The committing of each statement when it isfirst executed is very time consuming
? By setting AutoCommit to false, thedeveloper can update the database morethen once and then commit the entiretransaction as a whole
? Also, if each statement is dependant on theother, the entire transaction can be rolled
back and the user notified.
A transaction is when you have multiple statements that you want to have occur as ablock that in case of failure all of the changes would be rolled back
All or noneBy programming multiple update/inserts statements in a transactional manner, you will
get faster results because the call to a commit() slows down the process
2/21/2006
7/28/2019 13-JDBC_59
40/59
1
40
JDBC Transaction Methods
? setAutoCommit()
If set true, every executed statement iscommitted immediately
? commit()
Relevant only if setAutoCommit(false)
Commit operations performed since theopening of a Connection or last commit()or rollback() calls
? rollback()
Relevant only if setAutoCommit(false)
Cancels all operations performed
A transaction is when you have multiple statements that you want to have occur as ablock that in case of failure all of the changes would be rolled back
All or noneBy programming multiple update/inserts statements in a transactional manner, you will
get faster results because the call to a commit() slows down the process
2/21/2006
7/28/2019 13-JDBC_59
41/59
1
41
Transactions Example
Connection connection = null;try {
connection =DriverManager.getConnection("jdbc:oracle:thin:@machinename:1521:dbname","username","password");
connection.setAutoCommit(false);
PreparedStatement updateQty =connection.prepareStatement("UPDATE STORE_SALES SETQTY = ? WHERE ITEM_CODE = ? ");
To start a transaction, you create your PreparedStatement object asyou normally would.
The main difference here is that once you have the connectionobject, you turn off the Auto Committing feature,setAutoCommit(false)
1. Turned on by default
2/21/2006
7/28/2019 13-JDBC_59
42/59
1
42
Transaction Example cont.
int [][] arrValueToUpdate ={ {123, 500} ,
{124, 250},
{125, 10},
{126, 350} };
int iRecordsUpdate = 0;
for ( int items=0 ; items < arrValueToUpdate.length ;items++) {
int itemCode = arrValueToUpdate[items][0];
int qty = arrValueToUpdate[items][1];
Here, we create an array of integers (for a simple example). Thenloop through the array binding in each set of values.
2/21/2006
7/28/2019 13-JDBC_59
43/59
1
43
Transaction Example cont.
updateQty.setInt(1,qty);updateQty.setInt(2,itemCode);
iRecordsUpdate += updateQty.executeUpdate();
}
connection.commit();
System.out.println(iRecordsUpdate + " record(s) have beenupdated");
} catch(SQLException sqle) {
System.out.println("" + sqle);
Once each set is bound to the PreparedStatement object, then issuean executeUpdate() command on the statement.
If you dont call the commit() explicitly, then none of you changeswill be saved
2/21/2006
7/28/2019 13-JDBC_59
44/59
1
44
Transaction Example cont.
try { connection.rollback();
} catch(SQLException sqleRollback) {
System.out.println("" + sqleRollback);
}
}
finally {
try {
connection.close();
}
catch(SQLException sqleClose) {
System.out.println("" + sqleClose);
}
}
The entire process is wrapped in 1 try/catch block. The pointbehind this is that if there is a SQLException at any point, you cancatch this error and then rollback the entire batch as a whole.
Also, by closing the db connection in the finally statement, thisguarantees that in the event of a SQLException, that the dbconnection will not be left open.
2/21/2006
7/28/2019 13-JDBC_59
45/59
Prepared &Prepared &
Callable StatementsCallable Statements
2/21/2006
7/28/2019 13-JDBC_59
46/59
1
46
What Are They?
? PreparedStatement SQL is sent to the database and compiled or
prepared beforehand
? CallableStatement Executes SQL Stored Procedures
Once you get comfortable using the basic Statement object, try using the
PreparedStatement Object and the CallableStatement Object.
2/21/2006
7/28/2019 13-JDBC_59
47/59
1
47
PreparedStatement
? The contained SQL is sent to the database
and compiled or prepared beforehand? From this point on, the prepared SQL is sent
and this step is bypassed. The more dynamicStatement requires this step on everyexecution.
? Depending on the DB engine, the SQL maybe cached and reused even for a differentPreparedStatement and most of the work isdone by the DB engine rather than the driver
A PreparedStatement is very similar in concept to a regular Statement object.
In a practical application, using a PreparedStatement is the more preferred method to
executing SQL queries then the normal Statement object. Since the PreparedStatement
is prepared before usage and often reused by the database, it is faster then a Statement
object.
You can also change the input parameters of the statement without have to resend the
PreparedStatement to the database. So you basically prepare the statement once and
rebind in the variables every time you want to execute the same statement.
2/21/2006
7/28/2019 13-JDBC_59
48/59
1
48
PreparedStatement cont.
? A PreparedStatement can take INparameters, which act much likearguments to a method, for columnvalues.
? PreparedStatements deal with dataconversions that can be error prone instraight ahead, built on the fly SQL
handling quotes and dates in a mannertransparent to the developer
As I stated before, a PreparedStatement takes in parameters, much like arguments to a
method.
Another added bonus to using PreparedStatement, is that the underlying database
handles the data conversions. So instead of using all strings with a Statement object,
you can using native java types such as ints, longs, dates and so forth
2/21/2006
7/28/2019 13-JDBC_59
49/59
1
49
PreparedStatement Steps
1. You register the drive and create the db
connection in the usual manner
2. Once you have a db connection, createthe prepared statement object
PreparedStatement updateSales =con.prepareStatement(UPDATE OFFER_TBL SETQUANTITY = ? WHERE ORDER_NUM = ? ");
// ? are referred to as Parameter Markers// Parameter Markers are referred to by number,// starting from 1, in left to right order.// PreparedStatement's setXXX() methods are used to
set// the IN parameters, which remain set until changed.
The question marks are stand-ins for values to be set before statement execution and
are called parameter markers.
2/21/2006
7/28/2019 13-JDBC_59
50/59
1
50
PreparedStatement Steps cont.
3. Bind in your variables. The binding in ofvariables is positional based
updateSales.setInt(1, 75);
updateSales.setInt(2, 10398001);
4. Once all the vairables have been bound, thenyou execute the prepared statement
int iUpdatedRecords = updateSales.executeUpdate();
2/21/2006
7/28/2019 13-JDBC_59
51/59
1
51
PreparedStatement Steps
? If AutoCommit is set to true, once thestatement is executed, the changes arecommitted. From this point forth, youcan just re-use the Prepared Statementobject.
updateSales.setInt(1, 150);
updateSales.setInt(2,10398002);
2/21/2006
7/28/2019 13-JDBC_59
52/59
1
52
PreparedStatement cont.
? If the prepared statement object is a selectstatement, then you execute it, and loopthrough the result set object the same as inthe Basic JDBC example:
PreparedStatement itemsSold =con.prepareStatement("select o.order_num,o.customer_num, c.name, o.quantity from order_tbl o,customer_tbl c where o.customer_num =c.customer_num and o.customer_num = ?;");
itemsSold.setInt(1,10398001);
ResultSet rsItemsSold = itemsSold.executeQuery();
while (rsItemsSold.next()){
System.out.println( rsItemsSold.getString(NAME") + "sold "+ rsItemsSold.getString(QUANTITY") + " unit(s)");
}
For an update or insert, once you have the PreparedStatement object, you execute it as
often as you like. For example, if you have an array of ints, you could just loop through
the array, and at each call you could bind in your variables and call executeUpdate();
and maintain a summary style counter for the int return value. Then after the loop, you
would have a total of the number of records affected by your query.
2/21/2006
7/28/2019 13-JDBC_59
53/59
1
53
CallableStatement
? The interface used to execute SQLstored procedures
? A stored procedure is a group of SQLstatements that form a logical unit andperform a particular task
? Stored procedures are used toencapsulate a set of operations orqueries to execute on a databaseserver.
A CallableStatement extends PreparedStatement. So in essence, it works the same as the
PreparedStatement object. Since they share a lot of the same methods, once you are
comfortable using a PreparedStatement, the using a CallableStatement should be no different.
2/21/2006
7/28/2019 13-JDBC_59
54/59
1
54
CallableStatement cont.
? A CallableStatement object contains a call toa stored procedure; it does not contain thestored procedure itself.
? The first line of code below creates a call tothe stored procedure SHOW_SUPPLIERSusing the connection con .
? The part that is enclosed in curly braces isthe escape syntax for stored procedures.
CallableStatement cs = con.prepareCall("{callSHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
In this example, I am calling a stored procedure that returns a simple ResultSet object. The
executeQuery method is inherited from PreparedStatement.
2/21/2006
7/28/2019 13-JDBC_59
55/59
1
55
CallableStatement Example
Here is an example using IN, OUT and INOUT parameters
// set int IN parameter
cstmt.setInt( 1, 333 );
// register int OUT parameter
cstmt.registerOutParameter( 2, Types.INTEGER );
// set int INOUT parameter
cstmt.setInt( 3, 666 );
// register int INOUT parameter
cstmt.registerOutParameter( 3, Types.INTEGER );
//You then execute the statement with no return value
cstmt.execute(); // could use executeUpdate()
// get int OUT and INOUT
int iOUT = cstmt.getInt( 2 );
int iINOUT = cstmt.getInt( 3 );
Once very big difference between PreparedStatements and CallableStatements is
that with PreparedStatements you can only return 2 types of objects, a primitive
int and a resultSet (or nothing at all).
With CallableStatements, you have what is know as OUT and INOUT parameters.
You bind in your IN variables just as you would with a PreparedStatement. You
can have a stored procedure that return all different types of variables, NUMBER,
DATE, INTEGER etc.
OUT parameters are just like return variables. The value returned by the Stored
procedure is considered an OUT parameter, but you can also have the stored
procedure return multiple parameters
2/21/2006
7/28/2019 13-JDBC_59
56/59
1
56
Stored Procedure example
FUNCTION event_list (appl_id_in VARCHAR2,
dow_in VARCHAR2,
event_type_in VARCHAR2 OUT,
status_in VARCHAR2 INOUT)
RETURN ref_cur;
Here is an example of a stored procedure that has both IN, OUT and INOUT parameters
and it returns a Cursor of data (this is an oracle spec that just defines the layout of the
stored procedure)
In this case, you would bind in your input parameters (appl_id, dow_in) and your
INOUT parameter( status_in), you would also need to register your OUT parameters and
the INOUT (event_type_in and status_in)
Once you execute your statement, you retrieve your OUT values with the appropriate
getXXX method
2/21/2006
7/28/2019 13-JDBC_59
57/59
1
57
Oracle Example
?
This is an Oracle Specific example of aCallableStatement
try {
Connection connection = DriverManager.getConnection("");
CallableStatement queryreport = connection.prepareCall("{ ? =call SRO21208_PKG.QUEUE_REPORT ( ? , ? , ? , ? , ? , ? ) }");
queryreport.registerOutParameter(1,OracleTypes.CURSOR);
queryreport.setInt(2,10);
queryreport.setString(3, "000004357");
queryreport.setString(4, "01/07/2003");
queryreport.setString(5, "N");
queryreport.setString(6, "N");
queryreport.setString(7, "N");queryreport.setInt(8, 2);
This statement takes a couple of IN parameters and has 1 OUT parameter. The OUT
parameter is just an Oracle specific CURSOR
2/21/2006
7/28/2019 13-JDBC_59
58/59
1
58
Oracle Example cont.
queryreport.execute();ResultSet resultset = (ResultSet)queryreport.getObject(1);
while (resultset.next())
{
System.out.println("" + resultset.getString(1) + " " +resultset.getString(2));
}
}
catch( SQLException sqle)
{
System.out.println("" + sqle);
}
Once you have the ResultSet Object, you just loop through it in the normal manner
2/21/2006
7/28/2019 13-JDBC_59
59/59
59
Passion!Passion!
.
2/21/2006