SlideShare a Scribd company logo
1 of 24
JAVA & J2EE
J2EE
What is J2EE?
J2EE (Java 2 Enterprise Edition) is a specification for developing enterprise and distributed
applications from Sun Microsystems. J2EE is not one thing; it encompasses a large set of
technologies:
• JDBC
• Servlets
• JavaServer Pages (JSP)
• RMI(Remote Method Invokation)
• Enterprise JavaBeans (EJB)
• Java Naming and Directory Interface (JNDI)
• support for XML
• Java Messaging
• Java Transaction Support
• JavaMail
• Java support for CORBA
In this course, we will talk about JDBC , Servlets , JSP, RMI and EJB,
JDBC – Java DataBase Connectivity
What is JDBC?
The JDBC ( Java Database Connectivity) API (included in both J2SE and J2EE releases)defines
interfaces and classes that allow Java applications to access relational databases via SQL
commands and queries.
You must import java.sql package to reference them.
JDBC Architecture
The JDBC Architecture consists of two layers:
Java application calls the JDBC library, JDBC loads a driver which talks to the database.
What is JDBC Driver ?
To connect to the individual databases, JDBC API requires drivers for each database.
The JDBC Driver provides vendor-specific implementations of the abstract classes provided by
the JDBC API. This driver is used to connect to the database. i.e JDBC API communicates with
database through JDBC driver.
1
JAVA & J2EE
JDBC Driver Types
JDBC driver implementation vary because of the wide variety of OS and hardware platform in
which java operates. Some JDBC driver types are better suited for some applications than others.
There are currently four types of JDBC drivers each having its own use and limitations:
o Type1 JDBC-to-ODBC Driver
o Type 2 Java/Native Code driver
o Type 3 JDBC Driver
o Type 4 JDBC Driver
Type1 JDBC-to-ODBC Driver
− The JDBC-ODBC Driver also known as JDBC Type1 Driver
− Is a database driver that utilize the ODBC driver to connect to database
− Acts as a bridge between JDBC and another database connectivity mechanism such as ODBC
− Translates the JDBC API calls to ODBC API calls and sends them via native API calls
directly to the ODBC driver
− The driver is implemented in the sun.jdbc.odbc.JdbcOdbcDriver class
Advantages
The JDBC-ODBC Bridge allows access to almost any database, since the database’s ODBC
drivers are already available.
Disadvantages
1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then
to the database, and this applies even in the reverse process. They are the slowest of all driver
types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.
Type 2 Java/Native Code Driver
- JDBC type 2 driver also known as Java/Native code driver. It converts the JDBC calls in to
database specific calls
i.e. This driver is specific to a particular database such as oracle, informix, Sql Server, Sybase
E.g. oracle will have oracle native api
- Converts JDBC API calls to native API calls which are unique to the database.
- This driver communicates directly with databse
Advantage
- They are typically offer better performance than the JDBC- ODBC Bridge as the layers of
communication (tiers) are less than that of Type1 and also it uses Native api which is
2
JAVA & J2EE
Database specific.
Disadvantages
1. Native API must be installed in the Client System and hence type 2 drivers cannot be used for
the Internet.
2. Like Type 1 drivers, it’s not written in Java Language which forms a portability issue.
Type 3 JDBC Driver
− Also referred as the Java protocol.
− Converts the SQL queries into JDBC formatted statements and are translated into format
required by the DBMS
− 100% java driver
Advantages
1. This driver is fully written in Java and hence Portable. It is suitable for the web.
2. They are the most efficient amongst all driver types.
Type 4 JDBC Driver
− Also known as Type 4 database protocol
− Similar to type 3 jdbc driver except the sql queries are translated into format required by the
DBMS. i.e. Sql queries need not be tranaslted into JDBC formatted statements
Advantages
1. They are completely written in Java to achieve platform independence
2. Fastest way to communicate with database
3. Most suitable for the web.
JDBC packages
In order to connect to the database from Java, import the following packages:
java.sql.*; (usually enough)
javax.sql.* (for advanced features)
JDBC API are contained in the above two packages
Basic steps to access DataBase using JDBC
Before you can create a java JDBC connection to the datbase, you must first import the
java.sql package
import java.sql.*;
3
JAVA & J2EE
Accessing a database using JDBC involves a number of steps. You must write code to
perform the following steps:
1. Loading the JDBC driver
2. Connecting to the DBMS
3. Creating and executing the statement
4. Processing data returned by the DBMS
5. Terminating the connection with the DBMS
1. Loading the JDBC driver
In this step of the jdbc connection process, we load the driver class by calling Class.forName()
with the Driver class name as an argument. Once loaded, the Driver class creates an instance of
itself. A client can connect to Database Server through JDBC Driver. Since most of the Database
servers support ODBC driver therefore JDBC-ODBC Bridge driver is commonly used.
The return type of the Class.forName (String ClassName) method is “Class”. Class is a class in
java.lang package.
try {
// driver class for that specific database, say the SUN JDBC/ODBC Bridge driver:
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver");
}
catch { ClassNotFoundException cnfe) {
System.out.println(“Error loading driver”);
}
− Class.forName() method throws a ClassNotFoundException if an error occurs when loading
the JDBC driver
2. Connect to the DBMS
Next, the driver must connect to the DBMS. The JDBC DriverManager class defines objects
which can connect Java applications to a JDBC driver. DriverManager class manages the JDBC
drivers that are installed on the system. Its getConnection() method is used to establish a
connection to a database. It uses a username, password, and a jdbc url to establish a connection
to the database and returns a Connection object.
try{
Connection con = DriverManager.getConnection(
"jdbc:odbc:CustomerInformation", “username", “password" );
}
catch (SQLException e) {
System.out.println(“ can’t connect to
the database”);
4
JAVA & J2EE
}
Optional
jdbc URL consists of three parts:
jdbc:subprotocol:source
 jdbc which indicates that the JDBC protocol is to be used to read the URL
 <subprotocol> which is the jdbc driver name
 <source> which is the name used within the java program to connect to the database
A Connection object is returned by the getConnection() method if access is granted ;
otherwise, getConnection() method throws an SQLException
3. Creating and executing the statement
Once a connection is obtained we can interact with the database. Connection interface defines
methods for interacting with the database via the established connection. To execute SQL
statements, you need to instantiate a Statement object from your Connection object by using the
createStatement() method.
Statement stmt = con.createStatement( );
Statement interface defines methods that are used to interact with database via the execution of
SQL statements. To query the database, use the executeQuery() method of the Statement object.
This method takes a SQL statement as input and returns a JDBC ResultSet object.
ResultSet rs = stmt.executeQuery(“select * from Customers);
ResultSet contains the tuples of database table as a result of SQL query.
4. Processing data returned by the DBMS
• Once you run your query, use the next() method of the ResultSet object to iterate
through the results.
• This method steps through the result set row by row, detecting the end of the result
set when it is reached.
• To pull data out of the ResultSet as you iterate through it, use the appropriate getXXX methods
of the ResultSet object, that take a column index or column name and returns the data
while(rs.next()) {
// This will step through our data row-by-row
System.out.println(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3));
}
- First column has index 1, not 0
5. Terminate the connection to the databse
• Close the Connection,
Statement, and ResultSet.
5
JAVA & J2EE
Sample program – Quering a database( selecting rows)
import java.sql.*;
class QueryDataBase
{
public static void main(String[ ] args)
{
try
{
Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver" );
Connection con = DriverManager.getConnection( “jdbc:odbc:CustomerInfo, “ “ , “ ” );
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery( “Select * from Customers”);
while ( rs.next( ) )
{
String Fname = rs.getString( “FirstName" );
String Lname = rs.getString(“LastName”);
System.out.println(“First Name: “+FName+", Last Name: “+LName);
}
con.close() ;
stmt.close();
rs.close();
}
catch( Exception e )
{
System.out.println(e.getMessage());
}
}
}
Timeout
• Use setLoginTimeOut(int seconds) method to establish the maximum time the
DriverManger waits for a response from the DBMS before timing out.
• Use getLoginTimeOut(int seconds) method to retrieve from the Drivermanger the
maximum time the DriverManager is set to wait until it times out.
6
JAVA & J2EE
Associating the JDBC/ODBC bridge with the database
7
JAVA & J2EE
8
JAVA & J2EE
Connection Pooling Basics
• Establishing a connection for each user is slow and wasteful, and almost always
unnecessary
• Connection pooling is just a way to efficiently handle your database connection(JDBC
connection) by sharing it for different clients.
What is connection pooling?
A connection pool is a collection of database connections that are opened once and loaded into
memory so these connections can be reused without having to reconnect to the DBMS.
• Client applications request database connections from a pool
• The pool returns an already open connection to the application and marks it as “in-use”
9
JAVA & J2EE
• When the client application “closes” the connection, rather than actually closing the
connection it simply returns it to the pool, still connected for the next client
Connecting to a database using a pool connection
• Clients use the DataSource interface to interact with the connection pool.
• There are two types of connections made to the database
• Physical Connection
• Logical Connection
Context ctext = new InitialContext();
DataSource pool = (DataSource) ctext.lookup(“java: comp/env/jdbc/pool”);
Connection con = pool.getConnection();
// code to interact with database here
db.close();
Statement Objects
A Statement object is used to send and execute SQL statements to a database
Three kinds of Statements:
• Statement : Which executes simple sql queries without parameters.
• PreparedStatement : Which is used to execute a compiled query.
• CallableStatement: Which is used to execute a database stored procedure
All are interfaces, hence cannot be instantiated. They are created by Connection
The Statement Object
• Used whenever a J2EE component needs to immediately execute a query without first
having the query compiled.
• Statement every time compile the SQL and Execute.
• Before you can use a Statement object to execute a SQL statement, you need to create one
using the Connection object's createStatement( ) method
Statement stmt = con.createStatement();
• The Statement object cannot accept parameters.
• Once you've created a Statement object, you can then use it to execute a SQL statement with
one of its three execute methods:
executeQuery(), executeUpdate(), and execute().
• boolean execute(String SQL) :
Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false.
Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL.
Note: Statements that create a table, alter a table, or drop a table are all examples of DDL
10
JAVA & J2EE
• int executeUpdate(String SQL) :
Returns the number of rows affected by the execution of the SQL statement. Use this method to
execute SQL statements for which you expect to get a number of rows affected - for example, an
INSERT, UPDATE, or DELETE statement.
• ResultSet executeQuery(String SQL) :
Returns a ResultSet object. Use this method when you expect to get a result set, as you would
with a SELECT statement.
Example: To illustrate how to use the executeUpdate() method
import java.sql.*;
class EUDemo
{
public static void main(String[ ] args)
{
try
{
Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver" );
Connection con = DriverManager.getConnection( “jdbc:odbc:CustomerInfo, “ “ , “ ” );
Statement stmt = con.createStatement();
int rowsUpdated=stmt.executeUpdate( “UPDATE Customers SET PAID=‘y’ where
BALANCE=‘0’);
stmt.close();
con.close() ;
}
catch( Exception e )
{
System.out.println(e.getMessage());
}
}
}
PreparedStatement Object
• If we want to execute the same SQL statement several times, we can create a
PreparedStatement object:
• at the point of creation of a PreparedStatement object the SQL code is sent to the DB and
compiled. Subsequent executions may therefore be more efficient than normal statements
• PreparedStatements can take parameters
• Column values can be set after compilation
• Instead of values, use ‘?’ which is known as the parameter marker.
• Hence, Prepared Statements can be thought of as statements that contain placeholders to be
substituted later with actual values
• The setXXX() methods bind values to the parameters, where XXX represents the Java data
type of the value you wish to bind to the input parameter. If you forget to supply the values,
11
JAVA & J2EE
you will receive an SQLException.
• Each parameter marker is referred to by its ordinal position. The first marker represents
position 1, the next position 2, and so forth
• All of the Statement object's methods for interacting with the database
(a) execute(), (b) executeQuery(), and (c) executeUpdate() also work with the
PreparedStatement object
• As PreparedStatement inherits from Statement, the corresponding execute methods have no
parameters – execute(), executeQuery(), executeUpdate()
Example: To illustrate how to use PreparedStatement object
import java.sql.*;
class PSDemo
{
public static void main(String[ ] args)
{
try
{
Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver" );
Connection con = DriverManager.getConnection( “jdbc:odbc:CustomerInfo, “ “ , “ ” );
String query=“ SELECT * FROM Customers Where CustNumber = ? “;
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, “123”);
ResultSet rs=pstmt.executeQuery( );
int i=0;
while ( rs.next( ) )
{
i++;
System.out.println(rs.getString(i));
}
pstmt.close();
con.close() ;
}
catch( Exception e )
{
System.out.println(e.getMessage());
} } }
CallableStatement
A CallableStatement is a way to execute stored procedures from within a J2EE object.
Stored procedures :
A block of code with an assigned name that's stored in the database in compiled form so that
it can be shared by a number of programs and can be written in PL/SQL, T-SQL, C etc.
The stored procedure is executed by invoking the name of stored procedure.
{call <procedure-name>(<arg1>,<arg2>, …)}
12
JAVA & J2EE
The CallableStatement objects can use three types of parameters when calling a stored
procedure:
IN, OUT and INOUT.
Here are the definitions of each
Parameter Description
IN Contains data that needs to be passed to the stored procedure and whose value is
assigned using setxxx() method
OUT Contains the value returned by the stored procedure, if any. The OUT parameter
must be registered using the registerOutParameter() method and then later retrieved
using getxxx() method
INOUT A parameter that is used to both pass information to the stored procedure and
retrieve information from a stored procedure using above techniques
Example:
CallableStatement cstmt = conn.prepareCall(“{call LastOrderNumber(?)}”)
cstmt.registerOutParameter(1, Types.VARCHAR);
stmt.execute();
String lastOrderNumber=cstmt.getString(1);
− Always register OUT or INOUT parameters in stored procedures using rgisterOutParameter()
ResultSet
What is a ResultSet ?
An object that implemets ResultSet interface that contain data resulted from a SELECT query
statements and provide access to the generated data.
e.g. ResultSet rs = stmt.executeQuery(“select FirstName, LastName form Customers”);
− From this object, you can retrieve the value of columns by column name or position (starting
at 1).
– The data in a ResultSet object is organized in to a virtual table consisting of rows and
columns.
− In addition to data, the ResultSet object also contains metadata such as column names, column
size, and column data type.
− A ResultSet maintain a cursor pointing to row of the virtual table
13
JAVA & J2EE
− A J2EE component must have the virtual cursor to each row & then use other methods of the
ResultSet object to interact with the data stored in columns of that row
− The virtual cursor initially points before the first row and is moved to the first row by
the next()method
− The next() method can be used in a while loop to iterate through the result set.
− The next() method returns a boolean true if the row contains data; otherwise, a boolean
value false is returned indicating there are no more rows exists in the ResultSet
e.g. boolean Records = rs.next();
if(!Records)
{
System.out.println(“No data returned”);
System.exit(0);
}
while(rs.next())
{
// do something with one row
}
• Columns of the current row can be accessed by index (starting at 1) or name by using
getXXX() methods of the ResultSet object
• The XXX in getXXX() method is replaced with the the data type of the column that is to be
returned.
• The getXXX(…)methods can take a column name or the number of the column column
numbers start at 1
• getXXX(int columnIndex)
• returns the given field as the given type
• indices start at 1 and not 0!
• getXXX(String columnName)
• same, but uses name of field
• less efficient
For example:
getString(1) – returns the string data from the first column of the ResultSet
getInt(“Price”) - returns the integer data from the ‘Price’ column of the ResultSet
Sample program – Reading the ResultSet
import java.sql.*;
class QueryDataBase
{
public static void main(String[ ] args)
{
try
{
14
JAVA & J2EE
Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver" );
Connection con = DriverManager.getConnection( “jdbc:odbc:CustomerInfo, “ “ , “ ” );
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery( “select FirstName, LastName from Customers);
boolean Records = rs.next();
if(!Records)
{
System.out.println(“No data returned”);
System.exit(4);
}
while ( rs.next( ) )
{
String Fname = rs.getString( “FirstName" );
String Lname = rs.getString(“LastName”);
System.out.println(“First Name: “+FName+", Last Name: “+LName);
}
stmt.close();
con.close() ;
}
catch( Exception e )
{
System.out.println(e.getMessage());
}
}
}
Scrollable ResultSet
• JDBC 2.0 allows for scrolling through a ResultSet.
• Scrollable means that we can navigate forwards and backwards through the ResultSet
ResultSet navigation methods
The ResultSet interface provides methods for retrieving and manipulating the results of executed
queries
first() : Moves cursor to first row in the ResultSet
last() : Moves cursor to last row in the ResultSet
previous() : Moves cursor to previous row
absolute(int) : Moves cursor to a row index. If positive –counting
from the front, if negative –from the back
relative(int) : Moves cursor a relative number of rows, positive or
negative from the current position
getRow() : returns an integer that represents the number of row in the ResultSet
15
JAVA & J2EE
The ResultSet object can be setup to handle a scrollable ResultSet by passing the
createStatement() method one of three constants. These constants are:
• TYPE_FORWARD_ONLY
• TYPE_SCROLL_INSENSITIVE, and
• TYPE_SCROLL_SENSITIVE.
• TYPE_FORWARD_ONLY
− The result set is not scrollable i.e. the cursor moves only forward, from before the first
row to after the last row.
− Default setting
− Does not reflect changes made to the underlying data
e.g. Statement stmt = con.createStatement(TYPE_FORWARD_ONLY);
• TYPE_SCROLL_SENSITIVE
− The result set is scrollable; its cursor can move both forward and backward relative to
the current position, and it can move to an absolute position.
− Reflects changes made to the underlying data
e.g. Statement stmt = con.createStatement(TYPE_SCROLL_SENSITIVE);
• TYPE_SCROLL_INSENSITIVE
− The result set is scrollable; its cursor can move both forward and backward relative to the
current position, and it can move to an absolute position.
− Does notreflect changes made to the underlying data
e.g. Statement stmt = con.createStatement(TYPE_SCROLL_INSENSITIVE);
Sample program – using a scrollable ResultSet to query a database
import java.sql.*;
class QueryDataBase
{
public static void main(String[ ] args)
{
try
{
Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver" );
Connection con = DriverManager.getConnection( “jdbc:odbc:CustomerInfo, “ “ , “ ” );
Statement stmt = con.createStatement(TYPE_SCROLL_INSENSITIVE);
ResultSet rs = stmt.executeQuery( “select FirstName, LastName from Customers);
boolean Records = rs.next();
16
JAVA & J2EE
if(!Records)
{
System.out.println(“No data returned”);
System.exit(4);
}
while ( rs.next( ) )
{
rs.first(); // go to first row
rs.last(); // go to last row
rs.prevoius(); / / go to prevoius row
rs.absolute(10); / / go to 10th record
rs.relative(-2); / / go 2 records back
rs.relative(2); / / go 2 records forward
String Fname = rs.getString( “FirstName" );
String Lname = rs.getString(“LastName”);
System.out.println(“First Name: “+FName+", Last Name: “+LName);
}
stmt.close();
con.close() ;
}
catch( Exception e )
{
System.out.println(e.getMessage());
}
}
}
Updatable ResultSet
• JDBC 2.1 allows for updating (i.e. writing to the database through) a ResultSet.
• The ResultSet object can be setup to handle a updateable ResultSet by passing the
createStatement() method CONCUR_UPDATABLE constant , then we may be able to
update the database by modifying the ResultSet itself
e.g. Statement stmt = con.createStatement(CONCUR_UPDATABLE);
• Alternatively, the CONCUR_READ_ONLY constant can be passed to createStatement() to
prevent the ResultSet from being updated.
e.g. Statement stmt = con.createStatement(CONCUR_READ_ONLY);
There are three ways in which a ResultSet can be changed.
• Updating a row
• Inserting a new row
• Deleting a row
17
JAVA & J2EE
Updating ResultSet
• Like the getXXX(…)methods, the ResultSet has a wide range of updateXXX(…) methods to
change the value of column in the current row of the ResultSet
• The XXX in updateXXX() method is replaced with the data type of the column that is to be
updated.
• The updateXXX(…)methods requires two parameters.
• First parameter is either the column name or the number of the column of the ResultSet that is
being updated.
• Second parameter is the new value that will replace the value in the column of the ResultSet.
e.g. rs.updateString(“PRICE”, 40.0F); // changes the price of a product
Updating a row is a three step procedure:
• navigate to the appropriate row using a SELECT and ResultSet navigation methods
• update the field values in the ResultSet using updateXXX() methods
• Write the row using updateRow() method that changes the values in the current row of the
Resultset based on the values of the updateXXX() methods
e.g.
rs.first();
rs.updateFloat("PRICE", 40.0F);
rs.updateRow();
Deleting a row
 This is a simple two step procedure:
• navigate to row to be deleted
• delete the row using deleteRow() method
e.g.
rs.last();
rs.deleteRow();
• The deleteRow() method may passed an integer that contains
the number of the row to be deleted.
Inserting a row
 This is a three step procedure:
• navigate to insert row
• update the field values in the ResultSet using updatexxx() methods
• write the row to the ResultSet using insertRow() method
e.g.
rs.moveToInsertRow();
rs.updateString("NAME", "UML Distilled");
18
JAVA & J2EE
rs.updateString("ID", "0-201-32563-2");
rs.updateFloat("PRICE", 40.0F);
rs.insertRow();
Transaction Processing
• Transactions consist of a set of SQL statements that have been executed and completed . If
one fails, SQL statements that executed successfully up to that point in the transaction must be
rolled back.
• Transaction control is performed by the Connection object, default mode is auto-commit, In
previous examples ,each sql statement is treated as a transaction that will be committed
automatically when it has completed executing (auto commit is on)
• We can turn off the auto-commit mode with con.setAutoCommit(false) and turn it back on
with con.setAutoCommit(true);
• Once auto-commit is off, no SQL statement will be committed until an explicit is invoked
con.commit();
• At this point all changes done by the SQL statements will be made permanent in the database.
To use transactions:
- turn off automatic commit:
conn.setAutoCommit(false);
- execute operations
- if all operations succeeded, commit transaction:
conn.commit();
- else rollback transaction: con.rollback();
Transaction Example
con.setAutoCommit(false);
try {
PreparedStatement pstmt = con.prepareStatement(“update BankAccount
set amount=amount+? where accountId=?”);
pstmt.setInt(1,-100); pstmt.setInt(2, 13);
pstmt.executeUpdate();
pstmt.setInt(1, 100); pstmt.setInt(2, 72);
pstmt.executeUpdate();
con.commit();
}
catch (SQLException e) {
con.rollback();
}
19
JAVA & J2EE
Batch updates
• It was very inefficient for loading a lot of data into a DB – a separate SQL command had to be
executed for each record changed
• JDBC 2.0 allows batch updates
• multiple statements can be executed as a single batch
• we can roll back the whole batch if a single statement fails
• We simply add statements to be batched to a Statement or PreparedStatement object using
addBatch()
• The executeBatch() is called to execute entire batch at a time
• The executeBatch() method returns an int array that contains the number of SQL statements
that were executed successfully.
Batch update example
import java.sql.*;
class BatchUpdate
{
public static void main(String[ ] args)
{
Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver" );
Connection con = DriverManager.getConnection(jdbc:odbc:CustomerInformation “ ", “ " );
Statement s = con.createStatement();
try {
con.setAutoCommit( false );
s.addBatch(“UPDATE Customers SET Street = ‘5 Main Street’ “ +
“ Where FirstName=‘Bob’” );
s.addBatch(“UPDATE Custromers SET Street = ‘10 Main Street’ “ +
“Where FirstName=‘Tim’”);
int[ ] count = s.executeBatch( );
con.commit( );
}catch(Exception e )
{
con.rollback( );
}
finally{ con.close( ); s.close( ); } } }
Metadata
• Metadata is “data about the data”
Two types of Metadata
• Database Metadata- Describes the database
• ResultSet Metadata – Describes the ResultSet
20
JAVA & J2EE
Database Metadata
• Database metadata is the information that describes database itself
• This information may include the name of the driver, the DB URL, product name of the
database, names of the tables in DB, stored procedure names, primary keys etc.
Retrieving Database Metadata
• JDBC provides the DatabaseMetaData interface for obtaining database wide information
1. Get the DatabaseMetaData object.
DatabaseMetaData dbmd = conn.getMetaData();
2. Use the DatabaseMetaData object methods to retrieve specific metadata.
DatabaseMetaData dbmd = conn.getMetaData();
String s1 = dbmd.getURL();
String s2 = dbmd.getDatabaseProductName();
boolean b1 = dbmd.supportsTransactions();
String s3= dbmd.getDriverName()
ResultSet Metadata
• The ResultSet Metadata contains information about the columns in the result set
• This information may include the number and names of the columns, the types of the
columns
etc
How to Obtain Result Set Metadata
• JDBC provides the ResultSetMetaData interface for obtaining the information on the
specific ResultSet
1. Get the ResultSetMetaData object.
ResultSetMetaData rsmd = rset.getMetaData();
2. Use the ResultSetMetaData object methods to retrieve specific metadata.
ResultSetMetaData rsmd = rset.getMetaData();
for (int i = 0; i < rsmd.getColumnCount(); i++)
{
String colname = rsmd.getColumnName(i);
21
JAVA & J2EE
int coltype = rsmd.getColumnType(i);
…
}
Exception
There are three kinds of exceptions thrown by JDBC methods:
• SQL Exceptions – caused by SQL syntax error in the query
• SQL Warnings – throws warnings received by the Connection from the DBMS
• DataTruncation Exception – thrown whenever data is lost due to truncation of data value.
Review Questions
Q. What is JDBC ? What is the purpose of JDBC driver? Explain different types of JDBC
drivers?
Q. What packages are used by JDBC?
Q. Explain basic Steps in writing a Java program using JDBC?
or
Write step-by-step processes to connect a database using JDBC driver and explain
Q. Write a Java program to display the current contents of the table in a database using JDBC
Q. Assume that there is a table named as PRODUCT in MS-Access with the following fields
(PROD_ID,PROD_NAME, PRICE, VENDOR_NAME). Write a Java program to insert and
then display the records of this table using JDBC.
import java.sql.*;
class DBInsDispDemo
{
public static void main(String[ ] args)
{
try
{
Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver" );
Connection con = DriverManager.getConnection( “jdbc:odbc:ProductInfo, “ “ , “ ” );
Statement stmt = con.createStatement();
22
JAVA & J2EE
stmt.executeUpdate( “insert into PRODUCT ‘P111’, ‘HP Laptop’,’$950’,’AccuLogic’ );
ResultSet rs = stmt.executeQuery( “Select * from PRODUCT);
while ( rs.next( ) )
{
String PId = rs.getString( “PROD_ID" );
String PName = rs.getString(“PROD_NAME”);
String Price = rs.getString(“PRICE”);
String VName = rs.getString(“VENDOR_NAME”);
System.out.println(“PROD_ ID: “+PId+ "PROD_NAME: Pname+”PRICE:”+Price+
” VENDOR NAME:”+VName);
}
con.close() ;
stmt.close();
rs.close();
}
catch( Exception e )
{
System.out.println(e.getMessage());
}
}
}
Q. What are the steps in associating the JDBC/ODBC bridge with the database
Q. What is Connection Pooling? How to access a connection from a connection pool
Q. Explain three different types of JDBC statements
Q.What is execute(), executeUpdate() and executeQuery() methods
Q.What are prepared statements? Explain with example
Q.What are callable statements? Explain with example
Q. What is the difference between execute(), executeQuery() and executeUpdate()
Q. How do you call a stored procedure from JDBC?
Q. What is the difference between a Statement and a PreparedStatement?
Q. What is ResultSet? Explain with example how to read results from the ResultSet object
Q. Explain with example the Scrollable ResultSet?
Q. How to Make Updates to Updatable ResultSet?
Q. What is a transaction? Explain with example how to process a transaction?
or
How do transaction in JDBC happens
Q.What are batch updates? Explain with example
23
JAVA & J2EE
Q..What is Metadata and Explain how a J2EE component can access Database Metadata and
ResultSet MetaData
24

More Related Content

What's hot

JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)Talha Ocakçı
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1vikram singh
 
Java EE 01-Servlets and Containers
Java EE 01-Servlets and ContainersJava EE 01-Servlets and Containers
Java EE 01-Servlets and ContainersFernando Gil
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packagesvamsi krishna
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technologyvikram singh
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programmingKumar
 
Java servlets
Java servletsJava servlets
Java servletslopjuan
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtapVikas Jagtap
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsKaml Sah
 
Servlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servletsServlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servletsJavaEE Trainers
 

What's hot (20)

Java Servlets
Java ServletsJava Servlets
Java Servlets
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 
Jsp servlets
Jsp servletsJsp servlets
Jsp servlets
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
Java EE 01-Servlets and Containers
Java EE 01-Servlets and ContainersJava EE 01-Servlets and Containers
Java EE 01-Servlets and Containers
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
Java servlets
Java servletsJava servlets
Java servlets
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programming
 
Java servlets
Java servletsJava servlets
Java servlets
 
Servlets
ServletsServlets
Servlets
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
 
Servlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servletsServlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servlets
 
Servlets
ServletsServlets
Servlets
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Servlets
ServletsServlets
Servlets
 

Viewers also liked

Viewers also liked (6)

Java swing 1
Java swing 1Java swing 1
Java swing 1
 
Java Swing
Java SwingJava Swing
Java Swing
 
Java Swing
Java SwingJava Swing
Java Swing
 
java swing
java swingjava swing
java swing
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
Graphical User Interface (Gui)
Graphical User Interface (Gui)Graphical User Interface (Gui)
Graphical User Interface (Gui)
 

Similar to JDBC

Similar to JDBC (20)

Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
Unit 5-jdbc2
Unit 5-jdbc2Unit 5-jdbc2
Unit 5-jdbc2
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.ppt
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
Java Data Base Connectivity concepts.pptx
Java Data Base Connectivity concepts.pptxJava Data Base Connectivity concepts.pptx
Java Data Base Connectivity concepts.pptx
 
Jdbc new
Jdbc newJdbc new
Jdbc new
 
Prashanthi
PrashanthiPrashanthi
Prashanthi
 
jdbc
jdbcjdbc
jdbc
 
Core jdbc basics
Core jdbc basicsCore jdbc basics
Core jdbc basics
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
java database connection (jdbc)
java database connection (jdbc)java database connection (jdbc)
java database connection (jdbc)
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Jdbc complete
Jdbc completeJdbc complete
Jdbc complete
 

JDBC

  • 1. JAVA & J2EE J2EE What is J2EE? J2EE (Java 2 Enterprise Edition) is a specification for developing enterprise and distributed applications from Sun Microsystems. J2EE is not one thing; it encompasses a large set of technologies: • JDBC • Servlets • JavaServer Pages (JSP) • RMI(Remote Method Invokation) • Enterprise JavaBeans (EJB) • Java Naming and Directory Interface (JNDI) • support for XML • Java Messaging • Java Transaction Support • JavaMail • Java support for CORBA In this course, we will talk about JDBC , Servlets , JSP, RMI and EJB, JDBC – Java DataBase Connectivity What is JDBC? The JDBC ( Java Database Connectivity) API (included in both J2SE and J2EE releases)defines interfaces and classes that allow Java applications to access relational databases via SQL commands and queries. You must import java.sql package to reference them. JDBC Architecture The JDBC Architecture consists of two layers: Java application calls the JDBC library, JDBC loads a driver which talks to the database. What is JDBC Driver ? To connect to the individual databases, JDBC API requires drivers for each database. The JDBC Driver provides vendor-specific implementations of the abstract classes provided by the JDBC API. This driver is used to connect to the database. i.e JDBC API communicates with database through JDBC driver. 1
  • 2. JAVA & J2EE JDBC Driver Types JDBC driver implementation vary because of the wide variety of OS and hardware platform in which java operates. Some JDBC driver types are better suited for some applications than others. There are currently four types of JDBC drivers each having its own use and limitations: o Type1 JDBC-to-ODBC Driver o Type 2 Java/Native Code driver o Type 3 JDBC Driver o Type 4 JDBC Driver Type1 JDBC-to-ODBC Driver − The JDBC-ODBC Driver also known as JDBC Type1 Driver − Is a database driver that utilize the ODBC driver to connect to database − Acts as a bridge between JDBC and another database connectivity mechanism such as ODBC − Translates the JDBC API calls to ODBC API calls and sends them via native API calls directly to the ODBC driver − The driver is implemented in the sun.jdbc.odbc.JdbcOdbcDriver class Advantages The JDBC-ODBC Bridge allows access to almost any database, since the database’s ODBC drivers are already available. Disadvantages 1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable. 2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then to the database, and this applies even in the reverse process. They are the slowest of all driver types. 3. The client system requires the ODBC Installation to use the driver. 4. Not good for the Web. Type 2 Java/Native Code Driver - JDBC type 2 driver also known as Java/Native code driver. It converts the JDBC calls in to database specific calls i.e. This driver is specific to a particular database such as oracle, informix, Sql Server, Sybase E.g. oracle will have oracle native api - Converts JDBC API calls to native API calls which are unique to the database. - This driver communicates directly with databse Advantage - They are typically offer better performance than the JDBC- ODBC Bridge as the layers of communication (tiers) are less than that of Type1 and also it uses Native api which is 2
  • 3. JAVA & J2EE Database specific. Disadvantages 1. Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet. 2. Like Type 1 drivers, it’s not written in Java Language which forms a portability issue. Type 3 JDBC Driver − Also referred as the Java protocol. − Converts the SQL queries into JDBC formatted statements and are translated into format required by the DBMS − 100% java driver Advantages 1. This driver is fully written in Java and hence Portable. It is suitable for the web. 2. They are the most efficient amongst all driver types. Type 4 JDBC Driver − Also known as Type 4 database protocol − Similar to type 3 jdbc driver except the sql queries are translated into format required by the DBMS. i.e. Sql queries need not be tranaslted into JDBC formatted statements Advantages 1. They are completely written in Java to achieve platform independence 2. Fastest way to communicate with database 3. Most suitable for the web. JDBC packages In order to connect to the database from Java, import the following packages: java.sql.*; (usually enough) javax.sql.* (for advanced features) JDBC API are contained in the above two packages Basic steps to access DataBase using JDBC Before you can create a java JDBC connection to the datbase, you must first import the java.sql package import java.sql.*; 3
  • 4. JAVA & J2EE Accessing a database using JDBC involves a number of steps. You must write code to perform the following steps: 1. Loading the JDBC driver 2. Connecting to the DBMS 3. Creating and executing the statement 4. Processing data returned by the DBMS 5. Terminating the connection with the DBMS 1. Loading the JDBC driver In this step of the jdbc connection process, we load the driver class by calling Class.forName() with the Driver class name as an argument. Once loaded, the Driver class creates an instance of itself. A client can connect to Database Server through JDBC Driver. Since most of the Database servers support ODBC driver therefore JDBC-ODBC Bridge driver is commonly used. The return type of the Class.forName (String ClassName) method is “Class”. Class is a class in java.lang package. try { // driver class for that specific database, say the SUN JDBC/ODBC Bridge driver: Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver"); } catch { ClassNotFoundException cnfe) { System.out.println(“Error loading driver”); } − Class.forName() method throws a ClassNotFoundException if an error occurs when loading the JDBC driver 2. Connect to the DBMS Next, the driver must connect to the DBMS. The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager class manages the JDBC drivers that are installed on the system. Its getConnection() method is used to establish a connection to a database. It uses a username, password, and a jdbc url to establish a connection to the database and returns a Connection object. try{ Connection con = DriverManager.getConnection( "jdbc:odbc:CustomerInformation", “username", “password" ); } catch (SQLException e) { System.out.println(“ can’t connect to the database”); 4
  • 5. JAVA & J2EE } Optional jdbc URL consists of three parts: jdbc:subprotocol:source  jdbc which indicates that the JDBC protocol is to be used to read the URL  <subprotocol> which is the jdbc driver name  <source> which is the name used within the java program to connect to the database A Connection object is returned by the getConnection() method if access is granted ; otherwise, getConnection() method throws an SQLException 3. Creating and executing the statement Once a connection is obtained we can interact with the database. Connection interface defines methods for interacting with the database via the established connection. To execute SQL statements, you need to instantiate a Statement object from your Connection object by using the createStatement() method. Statement stmt = con.createStatement( ); Statement interface defines methods that are used to interact with database via the execution of SQL statements. To query the database, use the executeQuery() method of the Statement object. This method takes a SQL statement as input and returns a JDBC ResultSet object. ResultSet rs = stmt.executeQuery(“select * from Customers); ResultSet contains the tuples of database table as a result of SQL query. 4. Processing data returned by the DBMS • Once you run your query, use the next() method of the ResultSet object to iterate through the results. • This method steps through the result set row by row, detecting the end of the result set when it is reached. • To pull data out of the ResultSet as you iterate through it, use the appropriate getXXX methods of the ResultSet object, that take a column index or column name and returns the data while(rs.next()) { // This will step through our data row-by-row System.out.println(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3)); } - First column has index 1, not 0 5. Terminate the connection to the databse • Close the Connection, Statement, and ResultSet. 5
  • 6. JAVA & J2EE Sample program – Quering a database( selecting rows) import java.sql.*; class QueryDataBase { public static void main(String[ ] args) { try { Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver" ); Connection con = DriverManager.getConnection( “jdbc:odbc:CustomerInfo, “ “ , “ ” ); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery( “Select * from Customers”); while ( rs.next( ) ) { String Fname = rs.getString( “FirstName" ); String Lname = rs.getString(“LastName”); System.out.println(“First Name: “+FName+", Last Name: “+LName); } con.close() ; stmt.close(); rs.close(); } catch( Exception e ) { System.out.println(e.getMessage()); } } } Timeout • Use setLoginTimeOut(int seconds) method to establish the maximum time the DriverManger waits for a response from the DBMS before timing out. • Use getLoginTimeOut(int seconds) method to retrieve from the Drivermanger the maximum time the DriverManager is set to wait until it times out. 6
  • 7. JAVA & J2EE Associating the JDBC/ODBC bridge with the database 7
  • 9. JAVA & J2EE Connection Pooling Basics • Establishing a connection for each user is slow and wasteful, and almost always unnecessary • Connection pooling is just a way to efficiently handle your database connection(JDBC connection) by sharing it for different clients. What is connection pooling? A connection pool is a collection of database connections that are opened once and loaded into memory so these connections can be reused without having to reconnect to the DBMS. • Client applications request database connections from a pool • The pool returns an already open connection to the application and marks it as “in-use” 9
  • 10. JAVA & J2EE • When the client application “closes” the connection, rather than actually closing the connection it simply returns it to the pool, still connected for the next client Connecting to a database using a pool connection • Clients use the DataSource interface to interact with the connection pool. • There are two types of connections made to the database • Physical Connection • Logical Connection Context ctext = new InitialContext(); DataSource pool = (DataSource) ctext.lookup(“java: comp/env/jdbc/pool”); Connection con = pool.getConnection(); // code to interact with database here db.close(); Statement Objects A Statement object is used to send and execute SQL statements to a database Three kinds of Statements: • Statement : Which executes simple sql queries without parameters. • PreparedStatement : Which is used to execute a compiled query. • CallableStatement: Which is used to execute a database stored procedure All are interfaces, hence cannot be instantiated. They are created by Connection The Statement Object • Used whenever a J2EE component needs to immediately execute a query without first having the query compiled. • Statement every time compile the SQL and Execute. • Before you can use a Statement object to execute a SQL statement, you need to create one using the Connection object's createStatement( ) method Statement stmt = con.createStatement(); • The Statement object cannot accept parameters. • Once you've created a Statement object, you can then use it to execute a SQL statement with one of its three execute methods: executeQuery(), executeUpdate(), and execute(). • boolean execute(String SQL) : Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL. Note: Statements that create a table, alter a table, or drop a table are all examples of DDL 10
  • 11. JAVA & J2EE • int executeUpdate(String SQL) : Returns the number of rows affected by the execution of the SQL statement. Use this method to execute SQL statements for which you expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE statement. • ResultSet executeQuery(String SQL) : Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement. Example: To illustrate how to use the executeUpdate() method import java.sql.*; class EUDemo { public static void main(String[ ] args) { try { Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver" ); Connection con = DriverManager.getConnection( “jdbc:odbc:CustomerInfo, “ “ , “ ” ); Statement stmt = con.createStatement(); int rowsUpdated=stmt.executeUpdate( “UPDATE Customers SET PAID=‘y’ where BALANCE=‘0’); stmt.close(); con.close() ; } catch( Exception e ) { System.out.println(e.getMessage()); } } } PreparedStatement Object • If we want to execute the same SQL statement several times, we can create a PreparedStatement object: • at the point of creation of a PreparedStatement object the SQL code is sent to the DB and compiled. Subsequent executions may therefore be more efficient than normal statements • PreparedStatements can take parameters • Column values can be set after compilation • Instead of values, use ‘?’ which is known as the parameter marker. • Hence, Prepared Statements can be thought of as statements that contain placeholders to be substituted later with actual values • The setXXX() methods bind values to the parameters, where XXX represents the Java data type of the value you wish to bind to the input parameter. If you forget to supply the values, 11
  • 12. JAVA & J2EE you will receive an SQLException. • Each parameter marker is referred to by its ordinal position. The first marker represents position 1, the next position 2, and so forth • All of the Statement object's methods for interacting with the database (a) execute(), (b) executeQuery(), and (c) executeUpdate() also work with the PreparedStatement object • As PreparedStatement inherits from Statement, the corresponding execute methods have no parameters – execute(), executeQuery(), executeUpdate() Example: To illustrate how to use PreparedStatement object import java.sql.*; class PSDemo { public static void main(String[ ] args) { try { Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver" ); Connection con = DriverManager.getConnection( “jdbc:odbc:CustomerInfo, “ “ , “ ” ); String query=“ SELECT * FROM Customers Where CustNumber = ? “; PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, “123”); ResultSet rs=pstmt.executeQuery( ); int i=0; while ( rs.next( ) ) { i++; System.out.println(rs.getString(i)); } pstmt.close(); con.close() ; } catch( Exception e ) { System.out.println(e.getMessage()); } } } CallableStatement A CallableStatement is a way to execute stored procedures from within a J2EE object. Stored procedures : A block of code with an assigned name that's stored in the database in compiled form so that it can be shared by a number of programs and can be written in PL/SQL, T-SQL, C etc. The stored procedure is executed by invoking the name of stored procedure. {call <procedure-name>(<arg1>,<arg2>, …)} 12
  • 13. JAVA & J2EE The CallableStatement objects can use three types of parameters when calling a stored procedure: IN, OUT and INOUT. Here are the definitions of each Parameter Description IN Contains data that needs to be passed to the stored procedure and whose value is assigned using setxxx() method OUT Contains the value returned by the stored procedure, if any. The OUT parameter must be registered using the registerOutParameter() method and then later retrieved using getxxx() method INOUT A parameter that is used to both pass information to the stored procedure and retrieve information from a stored procedure using above techniques Example: CallableStatement cstmt = conn.prepareCall(“{call LastOrderNumber(?)}”) cstmt.registerOutParameter(1, Types.VARCHAR); stmt.execute(); String lastOrderNumber=cstmt.getString(1); − Always register OUT or INOUT parameters in stored procedures using rgisterOutParameter() ResultSet What is a ResultSet ? An object that implemets ResultSet interface that contain data resulted from a SELECT query statements and provide access to the generated data. e.g. ResultSet rs = stmt.executeQuery(“select FirstName, LastName form Customers”); − From this object, you can retrieve the value of columns by column name or position (starting at 1). – The data in a ResultSet object is organized in to a virtual table consisting of rows and columns. − In addition to data, the ResultSet object also contains metadata such as column names, column size, and column data type. − A ResultSet maintain a cursor pointing to row of the virtual table 13
  • 14. JAVA & J2EE − A J2EE component must have the virtual cursor to each row & then use other methods of the ResultSet object to interact with the data stored in columns of that row − The virtual cursor initially points before the first row and is moved to the first row by the next()method − The next() method can be used in a while loop to iterate through the result set. − The next() method returns a boolean true if the row contains data; otherwise, a boolean value false is returned indicating there are no more rows exists in the ResultSet e.g. boolean Records = rs.next(); if(!Records) { System.out.println(“No data returned”); System.exit(0); } while(rs.next()) { // do something with one row } • Columns of the current row can be accessed by index (starting at 1) or name by using getXXX() methods of the ResultSet object • The XXX in getXXX() method is replaced with the the data type of the column that is to be returned. • The getXXX(…)methods can take a column name or the number of the column column numbers start at 1 • getXXX(int columnIndex) • returns the given field as the given type • indices start at 1 and not 0! • getXXX(String columnName) • same, but uses name of field • less efficient For example: getString(1) – returns the string data from the first column of the ResultSet getInt(“Price”) - returns the integer data from the ‘Price’ column of the ResultSet Sample program – Reading the ResultSet import java.sql.*; class QueryDataBase { public static void main(String[ ] args) { try { 14
  • 15. JAVA & J2EE Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver" ); Connection con = DriverManager.getConnection( “jdbc:odbc:CustomerInfo, “ “ , “ ” ); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery( “select FirstName, LastName from Customers); boolean Records = rs.next(); if(!Records) { System.out.println(“No data returned”); System.exit(4); } while ( rs.next( ) ) { String Fname = rs.getString( “FirstName" ); String Lname = rs.getString(“LastName”); System.out.println(“First Name: “+FName+", Last Name: “+LName); } stmt.close(); con.close() ; } catch( Exception e ) { System.out.println(e.getMessage()); } } } Scrollable ResultSet • JDBC 2.0 allows for scrolling through a ResultSet. • Scrollable means that we can navigate forwards and backwards through the ResultSet ResultSet navigation methods The ResultSet interface provides methods for retrieving and manipulating the results of executed queries first() : Moves cursor to first row in the ResultSet last() : Moves cursor to last row in the ResultSet previous() : Moves cursor to previous row absolute(int) : Moves cursor to a row index. If positive –counting from the front, if negative –from the back relative(int) : Moves cursor a relative number of rows, positive or negative from the current position getRow() : returns an integer that represents the number of row in the ResultSet 15
  • 16. JAVA & J2EE The ResultSet object can be setup to handle a scrollable ResultSet by passing the createStatement() method one of three constants. These constants are: • TYPE_FORWARD_ONLY • TYPE_SCROLL_INSENSITIVE, and • TYPE_SCROLL_SENSITIVE. • TYPE_FORWARD_ONLY − The result set is not scrollable i.e. the cursor moves only forward, from before the first row to after the last row. − Default setting − Does not reflect changes made to the underlying data e.g. Statement stmt = con.createStatement(TYPE_FORWARD_ONLY); • TYPE_SCROLL_SENSITIVE − The result set is scrollable; its cursor can move both forward and backward relative to the current position, and it can move to an absolute position. − Reflects changes made to the underlying data e.g. Statement stmt = con.createStatement(TYPE_SCROLL_SENSITIVE); • TYPE_SCROLL_INSENSITIVE − The result set is scrollable; its cursor can move both forward and backward relative to the current position, and it can move to an absolute position. − Does notreflect changes made to the underlying data e.g. Statement stmt = con.createStatement(TYPE_SCROLL_INSENSITIVE); Sample program – using a scrollable ResultSet to query a database import java.sql.*; class QueryDataBase { public static void main(String[ ] args) { try { Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver" ); Connection con = DriverManager.getConnection( “jdbc:odbc:CustomerInfo, “ “ , “ ” ); Statement stmt = con.createStatement(TYPE_SCROLL_INSENSITIVE); ResultSet rs = stmt.executeQuery( “select FirstName, LastName from Customers); boolean Records = rs.next(); 16
  • 17. JAVA & J2EE if(!Records) { System.out.println(“No data returned”); System.exit(4); } while ( rs.next( ) ) { rs.first(); // go to first row rs.last(); // go to last row rs.prevoius(); / / go to prevoius row rs.absolute(10); / / go to 10th record rs.relative(-2); / / go 2 records back rs.relative(2); / / go 2 records forward String Fname = rs.getString( “FirstName" ); String Lname = rs.getString(“LastName”); System.out.println(“First Name: “+FName+", Last Name: “+LName); } stmt.close(); con.close() ; } catch( Exception e ) { System.out.println(e.getMessage()); } } } Updatable ResultSet • JDBC 2.1 allows for updating (i.e. writing to the database through) a ResultSet. • The ResultSet object can be setup to handle a updateable ResultSet by passing the createStatement() method CONCUR_UPDATABLE constant , then we may be able to update the database by modifying the ResultSet itself e.g. Statement stmt = con.createStatement(CONCUR_UPDATABLE); • Alternatively, the CONCUR_READ_ONLY constant can be passed to createStatement() to prevent the ResultSet from being updated. e.g. Statement stmt = con.createStatement(CONCUR_READ_ONLY); There are three ways in which a ResultSet can be changed. • Updating a row • Inserting a new row • Deleting a row 17
  • 18. JAVA & J2EE Updating ResultSet • Like the getXXX(…)methods, the ResultSet has a wide range of updateXXX(…) methods to change the value of column in the current row of the ResultSet • The XXX in updateXXX() method is replaced with the data type of the column that is to be updated. • The updateXXX(…)methods requires two parameters. • First parameter is either the column name or the number of the column of the ResultSet that is being updated. • Second parameter is the new value that will replace the value in the column of the ResultSet. e.g. rs.updateString(“PRICE”, 40.0F); // changes the price of a product Updating a row is a three step procedure: • navigate to the appropriate row using a SELECT and ResultSet navigation methods • update the field values in the ResultSet using updateXXX() methods • Write the row using updateRow() method that changes the values in the current row of the Resultset based on the values of the updateXXX() methods e.g. rs.first(); rs.updateFloat("PRICE", 40.0F); rs.updateRow(); Deleting a row  This is a simple two step procedure: • navigate to row to be deleted • delete the row using deleteRow() method e.g. rs.last(); rs.deleteRow(); • The deleteRow() method may passed an integer that contains the number of the row to be deleted. Inserting a row  This is a three step procedure: • navigate to insert row • update the field values in the ResultSet using updatexxx() methods • write the row to the ResultSet using insertRow() method e.g. rs.moveToInsertRow(); rs.updateString("NAME", "UML Distilled"); 18
  • 19. JAVA & J2EE rs.updateString("ID", "0-201-32563-2"); rs.updateFloat("PRICE", 40.0F); rs.insertRow(); Transaction Processing • Transactions consist of a set of SQL statements that have been executed and completed . If one fails, SQL statements that executed successfully up to that point in the transaction must be rolled back. • Transaction control is performed by the Connection object, default mode is auto-commit, In previous examples ,each sql statement is treated as a transaction that will be committed automatically when it has completed executing (auto commit is on) • We can turn off the auto-commit mode with con.setAutoCommit(false) and turn it back on with con.setAutoCommit(true); • Once auto-commit is off, no SQL statement will be committed until an explicit is invoked con.commit(); • At this point all changes done by the SQL statements will be made permanent in the database. To use transactions: - turn off automatic commit: conn.setAutoCommit(false); - execute operations - if all operations succeeded, commit transaction: conn.commit(); - else rollback transaction: con.rollback(); Transaction Example con.setAutoCommit(false); try { PreparedStatement pstmt = con.prepareStatement(“update BankAccount set amount=amount+? where accountId=?”); pstmt.setInt(1,-100); pstmt.setInt(2, 13); pstmt.executeUpdate(); pstmt.setInt(1, 100); pstmt.setInt(2, 72); pstmt.executeUpdate(); con.commit(); } catch (SQLException e) { con.rollback(); } 19
  • 20. JAVA & J2EE Batch updates • It was very inefficient for loading a lot of data into a DB – a separate SQL command had to be executed for each record changed • JDBC 2.0 allows batch updates • multiple statements can be executed as a single batch • we can roll back the whole batch if a single statement fails • We simply add statements to be batched to a Statement or PreparedStatement object using addBatch() • The executeBatch() is called to execute entire batch at a time • The executeBatch() method returns an int array that contains the number of SQL statements that were executed successfully. Batch update example import java.sql.*; class BatchUpdate { public static void main(String[ ] args) { Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver" ); Connection con = DriverManager.getConnection(jdbc:odbc:CustomerInformation “ ", “ " ); Statement s = con.createStatement(); try { con.setAutoCommit( false ); s.addBatch(“UPDATE Customers SET Street = ‘5 Main Street’ “ + “ Where FirstName=‘Bob’” ); s.addBatch(“UPDATE Custromers SET Street = ‘10 Main Street’ “ + “Where FirstName=‘Tim’”); int[ ] count = s.executeBatch( ); con.commit( ); }catch(Exception e ) { con.rollback( ); } finally{ con.close( ); s.close( ); } } } Metadata • Metadata is “data about the data” Two types of Metadata • Database Metadata- Describes the database • ResultSet Metadata – Describes the ResultSet 20
  • 21. JAVA & J2EE Database Metadata • Database metadata is the information that describes database itself • This information may include the name of the driver, the DB URL, product name of the database, names of the tables in DB, stored procedure names, primary keys etc. Retrieving Database Metadata • JDBC provides the DatabaseMetaData interface for obtaining database wide information 1. Get the DatabaseMetaData object. DatabaseMetaData dbmd = conn.getMetaData(); 2. Use the DatabaseMetaData object methods to retrieve specific metadata. DatabaseMetaData dbmd = conn.getMetaData(); String s1 = dbmd.getURL(); String s2 = dbmd.getDatabaseProductName(); boolean b1 = dbmd.supportsTransactions(); String s3= dbmd.getDriverName() ResultSet Metadata • The ResultSet Metadata contains information about the columns in the result set • This information may include the number and names of the columns, the types of the columns etc How to Obtain Result Set Metadata • JDBC provides the ResultSetMetaData interface for obtaining the information on the specific ResultSet 1. Get the ResultSetMetaData object. ResultSetMetaData rsmd = rset.getMetaData(); 2. Use the ResultSetMetaData object methods to retrieve specific metadata. ResultSetMetaData rsmd = rset.getMetaData(); for (int i = 0; i < rsmd.getColumnCount(); i++) { String colname = rsmd.getColumnName(i); 21
  • 22. JAVA & J2EE int coltype = rsmd.getColumnType(i); … } Exception There are three kinds of exceptions thrown by JDBC methods: • SQL Exceptions – caused by SQL syntax error in the query • SQL Warnings – throws warnings received by the Connection from the DBMS • DataTruncation Exception – thrown whenever data is lost due to truncation of data value. Review Questions Q. What is JDBC ? What is the purpose of JDBC driver? Explain different types of JDBC drivers? Q. What packages are used by JDBC? Q. Explain basic Steps in writing a Java program using JDBC? or Write step-by-step processes to connect a database using JDBC driver and explain Q. Write a Java program to display the current contents of the table in a database using JDBC Q. Assume that there is a table named as PRODUCT in MS-Access with the following fields (PROD_ID,PROD_NAME, PRICE, VENDOR_NAME). Write a Java program to insert and then display the records of this table using JDBC. import java.sql.*; class DBInsDispDemo { public static void main(String[ ] args) { try { Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver" ); Connection con = DriverManager.getConnection( “jdbc:odbc:ProductInfo, “ “ , “ ” ); Statement stmt = con.createStatement(); 22
  • 23. JAVA & J2EE stmt.executeUpdate( “insert into PRODUCT ‘P111’, ‘HP Laptop’,’$950’,’AccuLogic’ ); ResultSet rs = stmt.executeQuery( “Select * from PRODUCT); while ( rs.next( ) ) { String PId = rs.getString( “PROD_ID" ); String PName = rs.getString(“PROD_NAME”); String Price = rs.getString(“PRICE”); String VName = rs.getString(“VENDOR_NAME”); System.out.println(“PROD_ ID: “+PId+ "PROD_NAME: Pname+”PRICE:”+Price+ ” VENDOR NAME:”+VName); } con.close() ; stmt.close(); rs.close(); } catch( Exception e ) { System.out.println(e.getMessage()); } } } Q. What are the steps in associating the JDBC/ODBC bridge with the database Q. What is Connection Pooling? How to access a connection from a connection pool Q. Explain three different types of JDBC statements Q.What is execute(), executeUpdate() and executeQuery() methods Q.What are prepared statements? Explain with example Q.What are callable statements? Explain with example Q. What is the difference between execute(), executeQuery() and executeUpdate() Q. How do you call a stored procedure from JDBC? Q. What is the difference between a Statement and a PreparedStatement? Q. What is ResultSet? Explain with example how to read results from the ResultSet object Q. Explain with example the Scrollable ResultSet? Q. How to Make Updates to Updatable ResultSet? Q. What is a transaction? Explain with example how to process a transaction? or How do transaction in JDBC happens Q.What are batch updates? Explain with example 23
  • 24. JAVA & J2EE Q..What is Metadata and Explain how a J2EE component can access Database Metadata and ResultSet MetaData 24