Chapter 8 JDBC
Chapter 8 JDBC
Chapter 8 JDBC
Chapter 8
JDBC
8.1 Introduction
8.2 Design of JDBC
8.3 JDBC configuration
8.4 Executing SQL statement And Query Execution
8.5 Scrollable and updatable result sets
8.6 row sets
8.7 metadata
8.8 Transaction
8.1 Introduction
JDBC is a Java standard that provides the interface for connecting from Java to
relational databases. The JDBC standard is defined by Sun Microsystems and
implemented through the standard java.sql interfaces. This allows individual
providers to implement and extend the standard with their own JDBC drivers.
-independent connectivity between the Java programming language and a wide range of
databases.
The JDBC library includes APIs for each of the tasks commonly associated with
database usage:
JDBC API is a Java API that can access any kind of tabular data, especially data stored
in a Relational Database. JDBC works with Java on a variety of platforms, such as
Windows, Mac OS, and the various versions of UNIX.
JavaSoft's JDBC consists of two layers: the JDBC API and the JDBC Driver Manager API.
The JDBC API is the top layer and is the programming interface in Java to structured query
language (SQL) which is the standard for accessing relational databases.
The JDBC API communicates with the JDBC Driver Manager API, sending it various SQL
statements. The manager communicates (transparent to the programmer) with the various
third party drivers (provided by Database vendors like Oracle) that actually connect to the
database and return the information from the query.
JDBC Architecture:
The JDBC API supports both two-tier and three-tier processing models for database access
but in general JDBC Architecture consists of two layers:
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data
source. The driver manager is capable of supporting multiple concurrent drivers connected
to multiple heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application:
• Statement : You use objects created from this interface to submit the SQL
statements to the database. Some derived interfaces accept parameters in addition
to executing stored procedures.
• ResultSet: These objects hold data retrieved from a database after you execute an
SQL query using Statement objects. It acts as an iterator to allow you to move
through its data.
• SQLException: This class handles any errors that occur in a database application.
JDBC drivers implement the defined interfaces in the JDBC API for interacting with your
database server.
For example, using JDBC drivers enable you to open database connections and to
interact with it by sending SQL or database commands then receiving results with Java.
The Java.sql package that ships with JDK contains various classes with their
behaviours defined and their actual implementaions are done in third-party drivers.
Third party vendors implements the java.sql.Driver interface in their database
driver.
The JDBC-ODBC bridge that comes with JDK 1.2 is a good example of this kind of
driver.
You can think of the application server as a JDBC "proxy," meaning that it makes calls
for the client application. As a result, you need some knowledge of the application
server's configuration in order to effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the
database, understanding the nuances will prove helpful.
MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the
preferred driver type is 4.
If your Java application is accessing multiple types of databases at the same time, type
3 is the preferred driver.
Type 2 drivers are useful in situations where a type 3 or type 4 driver is not available yet
for your database.
The type 1 driver is not considered a deployment-level driver and is typically used for
development and testing purposes only.
After you've installed the appropriate driver, it's time to establish a database connection
using JDBC.
The programming involved to establish a JDBC connection is fairly simple. Here are
these simple four steps:
• Import JDBC Packages: Add import statements to your Java program to import
required classes in your Java code.
• Register JDBC Driver: This step causes the JVM to load the desired driver
implementation into memory so it can fulfill your JDBC requests.
• Database URL Formulation: This is to create a properly formatted address that
points to the database to which you wish to connect.
• Create Connection Object: Finally, code a call to the DriverManager object's
getConnection( ) method to establish actual database connection.
The Import statements tell the Java compiler where to find the classes you reference in
your code and are placed at the very beginning of your source code.
To use the standard JDBC package, which allows you to select, insert, update, and
delete data in SQL tables, add the following imports to your source code:
import java.sql.* ; // for standard JDBC programs
import java.math.* ; // for BigDecimal and BigInteger support
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
You can use getInstance() method to work around noncompliant JVMs, but
then you'll have to code for two extra Exceptions as follows:
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstanc
e();
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver
class!");
System.exit(1);
catch(IllegalAccessException ex) {
System.out.println("Error: access problem while
loading!");
System.exit(2);
catch(InstantiationException ex) {
System.out.println("Error: unable to instantiate
driver!");
System.exit(3);
}
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
Mr. Mayur Kharik
Advanced Java Programming
Here each form requires a database URL. A database URL is an address that points to
your database.
Formulating a database URL is where most of the problems associated with establishing
a connection occur.
Following table lists down popular JDBC driver names and database URL.
All the highlighted part in URL format is static and you need to change only remaining
part as per your database setup.
Now you have to call getConnection() method with appropriate username and
Mr. Mayur Kharik
Advanced Java Programming
However, in this case, the database URL includes the username and password and has
the following general form:
jdbc:oracle:driver:username/password@database
A Properties object holds a set of keyword-value pairs. It's used to pass driver properties
to the driver during a call to the getConnection() method.
To make the same connection made by the previous examples, use the following code:
import java.util.*;
String URL = "jdbc:oracle:thin:@amrood:1521:EMP";
Properties info = new Properties( );
info.put( "user", "username" );
info.put( "password", "password" );
Explicitly closing a connection conserves DBMS resources, which will make your
database administrator happy.
Once a connection is obtained we can interact with the database. The JDBC Statement,
CallableStatement, and PreparedStatement interfaces define the methods and
properties that enable you to send SQL or PL/SQL commands and receive data from
your database.
They also define methods that help bridge data type differences between Java and SQL
data types used in a database.
Following table provides a summary of each interface's purpose to understand how do
you decide which interface to use?
try {
stmt = conn.createStatement( );
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}
Once you've created a Statement object, you can then use it to execute a SQL
statement with one of its three execute methods.
• 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.
• int executeUpdate(String SQL) : Returns the numbers 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.
All parameters in JDBC are represented by the ? symbol, which is known as the
parameter marker. You must supply values for every parameter before executing the
SQL statement.
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, 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. This method differs from that of Java array
indices, which start at 0.
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. However, the methods are modified
to use SQL statements that can take input the parameters.
pstmt = conn.prepareStatement(SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
pstmt.close();
}
DELIMITER ;
Three types of parameters exist: IN, OUT, and INOUT. The PreparedStatement object
only uses the IN parameter. The CallableStatement object can use all three.
Here are the definitions of each:
Parameter Description
A parameter whose value is unknown when the SQL statement is created. You bind
IN
values to IN parameters with the setXXX() methods.
A parameter whose value is supplied by the SQL statement it returns. You retrieve values
OUT
from theOUT parameters with the getXXX() methods.
A parameter that provides both input and output values. You bind variables with the
INOUT
setXXX() methods and retrieve values with the getXXX() methods.
The String variable SQL represents the stored procedure, with parameter placeholders.
Using CallableStatement objects is much like using PreparedStatement objects.
You must bind values to all parameters before executing the statement, or you will
receive an SQLException.
If you have IN parameters, just follow the same rules and techniques that apply to a
PreparedStatement object; use the setXXX() method that corresponds to the Java
data type you are binding.
When you use OUT and INOUT parameters you must employ an additional
CallableStatement method, registerOutParameter(). The
registerOutParameter() method binds the JDBC data type to the data type the
stored procedure is expected to return.
Once you call your stored procedure, you retrieve the value from the OUT parameter
with the appropriate getXXX() method. This method casts the retrieved value of SQL
type to a Java data type.
A simple call to the close() method will do the job. If you close the Connection object
first it will close the CallableStatement object as well. However, you should always
explicitly close the CallableStatement object to ensure proper cleanup.
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
cstmt.close();
}
The SQL statements that read data from a database query return the data in a result set.
The SELECT statement is the standard way to select rows from a database and view
them in a result set. The java.sql.ResultSet interface represents the result set of a
database query.
A ResultSet object maintains a cursor that points to the current row in the result set. The
term "result set" refers to the row and column data contained in a ResultSet object.
The methods of the ResultSet interface can be broken down into three categories:
• Navigational methods: used to move the cursor around.
• Get methods: used to view the data in the columns of the current row being pointed to
by the cursor.
• Update methods: used to update the data in the columns of the current row. The
updates can then be updated in the underlying database as well.
The cursor is movable based on the properties of the ResultSet. These properties are
designated when the corresponding Statement that generated the ResultSet is created.
JDBC provides following connection methods to create statements with desired
ResultSet:
• createStatement(int RSType, int RSConcurrency);
• prepareStatement(String SQL, int RSType, int RSConcurrency);
• prepareCall(String sql, int RSType, int RSConcurrency);
The first argument indicate the type of a ResultSet object and the second argument is
one of two ResultSet constants for specifying whether a result set is read-only or
updatable.
Example-
/***************************************************************/
//This example was coded and tested with JDK
//Access was used as database, over the JDBC-ODBC bridge which
//comes with the JDK.
//To run this example, you need a database with the following
//properties:
//=> a table called "Cust"
//=> a system DSN called "Database"
/***************************************************************/
import java.sql.* ;
class JDBCQuery
{
public static void main( String args[] )
{
try
{
// Load the database driver
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" ) ;
se = se.getNextException() ;
}
}
catch( Exception e )
{
System.out.println( e ) ;
}
}
}
on the basis of ResultSet cursor movement there are two types of ResultSets
This ResultSet will allow users only to iterate the data in forward direction.To refer this
ResultSet object ResultSet interface has provided the following constant.
ii)scrollable ResultSets:
These ResultSet objects will allow the users to interact the data in both forward and
backward directions.
a)ScrollSensitive ResultSet:
To represent this ResultSet object we have to use the following constant from
ResultSet interface.
b)ScrollInSensitive ResultSet:
These are scrollable ResultSetss objects, which will allow the later
database modifications after creation.
To represent this ResultSet object we have to use the following constant from
ResultSet interface.
This ResultSet will allow the users only to read the data.To represent this
ResultSet object we have to use following constant from ResultSet interface.
ii)updatable ResultSet:
This ResultSet object will allow user to perform updation on it’s content.
If you want to specify particular ResultSet type in JDBC applications then we have to
specify the type of ResultSet object at the time of creation of statement object.
To refresh present report a scroll sensitive ResultSet object we have to use the
following method.
To move ResultSet cursor after last record position we have to use following method
To move ResultSet cursor to first record position we will use the following method
To move ResultSet cursor to last record position we will use the following method
Mr. Mayur Kharik
Advanced Java Programming
To move ResultSet cursor to a particular record position we will use the following
method
To skip particular no.of records from the current position of the ResultSet we have to use
the following method
note:If the int value is positive then ResultSet cursor will move in forward direction, if it is
negative then ResultSet cursor will move in backward direction.
To insert new row in updatable ResultSet object we have to use following method
In order to make temporary insertion as permanent insertion in the ResultSet object and
database we have to use following method.
Example program - 1 :
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
Statement
st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.
CONCUR_UPDATABLE);
Mr. Mayur Kharik
Advanced Java Programming
note:
Example program - 2 :
package com.visualbuilder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,Re
sultSet.CONCUR_UPDATABLE);
while(rs.next()) {
System.out.print("Id is " + rs.getInt("id"));
System.out.println(" Name is
"+rs.getString("name"));
}
rs.absolute(1);
rs.updateString(2,"Visual Builder");
rs.updateRow();
rs.beforeFirst();
System.out.println("After Updation");
while(rs.next()) {
System.out.print("Id is " + rs.getInt("id"));
System.out.println(" Name is
"+rs.getString("name"));
}
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:-
Id is 3 Name is Eclipse
Id is 4 Name is IBM
Id is 5 Name is Jakarta
After Updation
Id is 3 Name is Eclipse
Id is 4 Name is IBM
Id is 5 Name is Jakarta
A RowSet object is a java bean component and extends the ResultSet interface
Thus, it has a set of JavaBeans properties and follows the JavaBeans event model. A
RowSet object's properties allow it to establish its own database connection and to
execute its own query in order to fill itself with data
Types of Rowset
The RowSet is majorly classified into two types as per their properties:-
1. Passing the ResultSet:- In this approach the data is populated in the object and then
you can retrieve the data by using the getter methods as we did in case of the ResultSet.
Exmple:-
2. Creating the default object:- This approach is useful if you want to set the data
sources dynamically. In this approach the Database URL, username and password is
explicitly set in the RowSetObject.
Exmple:-
jdbcRs.setUsername("user");
jdbcRs.setPassword("password");
jdbcRs.setUrl("jdbc:mySubprotocol:mySubname");
jdbcRs.execute();
The following example will illustrate the basic operation using the JDBCRowSet
interface.
import java.sql.SQLException;
import javax.sql.rowset.JdbcRowSet;
import com.sun.rowset.JdbcRowSetImpl;
jdbcRs.setUsername("scott");
jdbcRs.setPassword("tiger");
jdbcRs.setUrl("jdbc:odbc:MyDsn");
jdbcRs.execute();
while(jdbcRs.next()) {
System.out.println(jdbcRs.getString("ename"));
}
}
}
Ouput:-
Adam
Susan
Adran
Hardy
Tim
Michael
8.7 metadata
Definition:
Data about the data is called as metadata.In JDBC there are two types of metadata.
1.Database metadata
2.ResultSet metadata.
JDBC Meta Data is the collective information about the data structure and property of a
column available in table. The meta data of any table tells you the name of the
columns,datatype used in column and constraint used to enter the value of data into
column of the table.
the list of methods to get the meta data property of table as given follow -
Loading a driver by calling a class.forname( ),this accept driver class as argument.
DriverManager.getConnection ( ) -This method return you a connection object and
built a connection between url and database. Once a connection is built, a front end can
access, insert ,update and retrieve the data in the backend database.
con.createStatement ( ) -This is used to create a sql object. An object of connection
class is used to send and create a sql query in the database backend.
executeQuery ( ) -The method retrieve a record set from a table in database. The
retrieve record set is assigned to a result set.
getMetaData ( ) - The Result Set call get Metadata( ),which return you the property
of the retrieve record set (length,field,column).Meta Data account for data element and
its attribute.
getcolumncount ( ) -The method return you a integer data type and provides you the
number of column in the Result set object.
Finally the println print the table name, field, size and data type.
In case there is an exception in the try block The subsequent catch block caught and
handle the exception.
JdbcMetaDataGettables.java
import java.sql.*;
"jdbc:mysql://localhost:3306/test";
try {
Class.forName(driver);
Connection con =
DriverManager.getConnection(connection, user,password);
Statement st = con.createStatement();
Mr. Mayur Kharik
Advanced Java Programming
ResultSet rs = st.executeQuery(sql);
System.out.println("Field \tsize\tDataType");
System.out.print(metaData.getColumnName(i + 1) +
"\t");
System.out.print(metaData.getColumnDisplayS ize(i + 1)
+"\t");
System.out.println(metaData.getColumnTypeNa me(i +
1));
} catch (Exception e) {
System.out.println(e);
Output:-
Table Name:person
Field Size DataTypes
id 2 VARCHAR
cname 50 VARCHAR
dob 10 DATE
8.8 Transaction
The ACID properties describes the transaction management well. ACID stands for
Atomicity, Consistency, isolation and durability.
Consistency ensures bringing the database from one consistent state to another
consistent state.
Durability means once a transaction has been committed, it will remain so, even in the
event of errors, power loss etc.
fast performance It makes the performance fast because database is hit at the time of
commit.
Method Description
import java.sql.*;
class FetchRecords{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@
localhost:1521:xe","system","oracle");
con.setAutoCommit(false);
Statement stmt=con.createStatement();
con.commit();
con.close();
}}
If you see the table emp400, you will see that 2 records has been added.
import java.sql.*;
import java.io.*;
class TM{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thi
n:@localhost:1521:xe","system","oracle");
con.setAutoCommit(false);
while(true){
System.out.println("enter id");
String s1=br.readLine();
int id=Integer.parseInt(s1);
System.out.println("enter name");
String name=br.readLine();
System.out.println("enter salary");
String s3=br.readLine();
int salary=Integer.parseInt(s3);
ps.setInt(1,id);
ps.setString(2,name);
Mr. Mayur Kharik
Advanced Java Programming
ps.setInt(3,salary);
ps.executeUpdate();
System.out.println("commit/rollback");
String answer=br.readLine();
if(answer.equals("commit")){
con.commit();
if(answer.equals("rollback")){
con.rollback();
String ans=br.readLine();
if(ans.equals("n")){
break;
con.commit();
}catch(Exception e){System.out.println(e);}
}}
It will ask to add more records until you press n. If you press n, transaction is committed.