JDBC Notes
JDBC Notes
JDBC Notes
JDBC is a Java API that is used to connect and execute the query to the database. JDBC API uses
JDBC drivers to connect to the database. JDBC API can be used to access tabular data stored into any relational
database.
JDBC Driver
JDBC Driver is a software component that enables java application to interact with the database. There are 4
types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC
bridge driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of
thin driver.
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use JDBC drivers
provided by the vendor of your database instead of the JDBC-ODBC Bridge.
Advantages:
o Easy to use.
o Can be easily connected to any database.
Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC function calls.
o The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method
calls into native calls of the database API. It is not written entirely in java.
Advantage:
o Performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
o The Native driver needs to be installed on the each client machine.
o The Vendor client library needs to be installed on client machine.
The Network Protocol driver uses middleware (application server) that converts JDBC calls directly
or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
o No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.
Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires database-specific coding
to be done in the middle tier.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it
is known as thin driver. It is fully written in Java language.
Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.
Disadvantage:
o Drivers depend on the Database.
Java Database Connectivity with 6 Steps
There are 6 steps to connect any java application with the database using JDBC. These steps are as follows:
o Importing JDBC package
o Load/Register the Driver class
o Establish the connection
o Create statement
o Execute queries
o Close connection
We need to import java.sql.* package of JDBC to use all the classes and Interfaces available in that package
to establish the communication with any database vendor through java application.
Loading:
The forName() method of the Class class is used to Load the driver class. This method is used to load the
driver class dynamically.
Ex: Class.forName("oracle.jdbc.driver.OracleDriver");
Registering:
The registerDriver() method of DriverManager class is used to register the dirver class object.
The getConnection() method of DriverManager class is used to establish the connection with the database.
The syntax of the getConnection() method is given below.
Consider the following example to establish the connection with the Oracle database.
Connection con=
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","password");
The createStatement() method of Connection interface is used to create the Statement. The object of the
Statement is responsible for executing queries with the database.
The executeQuery() method of Statement interface is used to execute queries to the database. This method
returns the object of ResultSet that can be used to get all the records of a table.
6. Closing connection:
By closing connection, object statement and ResultSet will be closed automatically. The close() method of
Connection interface is used to close the connection.
The java.sql package contains following interfaces and classes for JDBC API.
Interfaces:
Statement: The Statement object is created by using createStatement() method of Connection class.
The Connection interface is the factory for Statement.
ResultSet: The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor
points before the first row. The executeQuery() method of Statement interface returns the ResultSet
object.
ResultSetMetaData: The object of ResultSetMetaData interface cotains the information about the
data (table) such as numer of columns, column name, column type, etc. The getMetaData() method of
ResultSet returns the object of ResultSetMetaData.
Classes:
o DriverManager: The DriverManager class acts as an interface between the user and drivers. It keeps
track of the drivers that are available and handles establishing a connection between a database and
the appropriate driver. It contains several methods to keep the interaction between the user and drivers.
o Blob: Blob stands for the binary large object. It represents a collection of binary data stored as a single
entity in the database management system.
o Clob: Clob stands for Character large object. It is a data type that is used by various database
management systems to store character files. It is similar to Blob except for the difference that BLOB
represent binary data such as images, audio and video files, etc. whereas Clob represents character
stream data such as character files, etc.
1. Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database
is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database, thin is the
driver, localhost is the server name on which oracle is running, we may also use IP address, 1521 is
the port number and XE is the Oracle service name. You may get all these information from the
tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the oracle database.
Create a Table
Before establishing connection, let's first create a table in oracle database. Following is the SQL query to
create a table.
In this example, we are connecting to an Oracle database and getting data from emp table.
Here, system and oracle are the username and password of the Oracle database.
import java.sql.*;
class OracleCon
{
public static void main(String args[])
{
Try
{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch(Exception e)
{
System.out.println(e);
}
}
}
The above example will fetch all the records of emp table.
To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.
Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here.
2) set classpath:
Firstly, search the ojdbc14.jar file then open command prompt and write:
C:>set classpath=c:\folder\ojdbc14.jar;.;
Go to environment variable then click on new tab. In variable name write classpath and in variable
value paste the path to ojdbc14.jar by appending ojdbc14.jar;.;
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;.;
JDBC Package
DriverManager class
The DriverManager class acts as an interface between user and drivers. It keeps track of the drivers that are
available and handles establishing a connection between a database and the appropriate driver. The
DriverManager class maintains a list of Driver classes that have registered themselves by calling the method
DriverManager.registerDriver().
Method Description
1) public static void registerDriver(Driver driver): is used to register the given driver with
DriverManager.
2) public static void deregisterDriver(Driver is used to deregister the given driver (drop the
driver): driver from the list) with DriverManager.
3) public static Connection getConnection(String is used to establish the connection with the
url): specified url.
4) public static Connection getConnection(String is used to establish the connection with the
url,String userName,String password): specified url, username and password.
Connection interface
A Connection is the session between java application and database. The Connection interface is a
factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection can be used to get
the object of Statement and DatabaseMetaData. The Connection interface provide many methods for
transaction management like commit(), rollback() etc.
1) public Statement createStatement(): creates a statement object that can be used to execute SQL queries.
2) public Statement createStatement(int resultSetType,int resultSetConcurrency): Creates a Statement
object that will generate ResultSet objects with the given type and concurrency.
3) public void setAutoCommit(boolean status): is used to set the commit status.By default it is true.
4) public void commit(): saves the changes made since the previous commit/rollback permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources immediately.
Statement interface
The Statement interface provides methods to execute queries with the database. The statement interface is a
factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object of
ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create, drop, insert,
update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple results.
Let’s see the simple example of Statement interface to insert, update and delete the record.
import java.sql.*;
class FetchRecord
{
public static void main(String args[])throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Statement stmt=con.createStatement();
PreparedStatement interface
As you can see, we are passing parameter (?) for the values. Its value will be set by calling the setter methods
of PreparedStatement.
Improves performance: The performance of the application will be faster if you use PreparedStatement
interface because query is compiled only once.
The prepareStatement() method of Connection interface is used to return the object of PreparedStatement.
Syntax:
Method Description
public void setInt(int paramIndex, int value) sets the integer value to the given parameter
index.
public void setString(int paramIndex, String value) sets the String value to the given parameter
index.
public void setFloat(int paramIndex, float value) sets the float value to the given parameter
index.
public void setDouble(int paramIndex, double value) sets the double value to the given parameter
index.
public int executeUpdate() executes the query. It is used for create, drop,
insert, update, delete etc.
public ResultSet executeQuery() executes the select query. It returns an
instance of ResultSet.
import java.sql.*;
class InsertPrepared
{
public static void main(String args[])
{
Try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe
","system","oracle");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
CallableStatement Interface
CallableStatement interface is used to call the stored procedures and functions.
We can have business logic on the database by the use of stored procedures and functions that will
make the performance better because these are precompiled.
Suppose you need the get the age of the employee based on the date of birth, you may create a function
that receives date as the input and returns age of the employee as the output.
The prepareCall() method of Connection interface returns the instance of CallableStatement. Syntax is given
below:
public CallableStatement prepareCall("{ call procedurename(?,?...?)}");
In this example, we are going to call the stored procedure INSERTR that receives id and name as the
parameter and inserts it into the table user420. Note that you need to create the user420 table as well to run
this application.
import java.sql.*;
public class Proc
{
public static void main(String[] args) throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
System.out.println("success");
}
}
Now check the table in the database, value is inserted in the user420 table.
In this example, we are calling the sum4 function that receives two input and returns the sum of the given
number. Here, we have used the registerOutParameter method of CallableStatement interface, that registers
the output parameter with its corresponding type. It provides information to the CallableStatement about the
type of result being displayed.
The Types class defines many constants such as INTEGER, VARCHAR, FLOAT, DOUBLE, BLOB, CLOB
etc.
import java.sql.*;
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
System.out.println(stmt.getInt(1));
}
}
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to before
the first row.
Note: By default, ResultSet object can be moved forward only and it is not updatable.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int) method as
well as we can make this object as updatable by:
1) public boolean next(): is used to move the cursor to the one row
next from the current position.
2) public boolean previous(): is used to move the cursor to the one row
previous from the current position.
3) public boolean first(): is used to move the cursor to the first row
in result set object.
4) public boolean last(): is used to move the cursor to the last row
in result set object.
5) public boolean absolute(int row): is used to move the cursor to the specified
row number in the ResultSet object.
6) public boolean relative(int row): is used to move the cursor to the relative
row number in the ResultSet object, it may
be positive or negative.
7) public int getInt(int columnIndex): is used to return the data of specified
column index of the current row as int.
8) public int getInt(String columnName): is used to return the data of specified
column name of the current row as int.
9) public String getString(int columnIndex): is used to return the data of specified
column index of the current row as String.
10) public String getString(String columnName): is used to return the data of specified
column name of the current row as String.
import java.sql.*;
class FetchRecord
{
public static void main(String args[])throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syste
m","oracle");
Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs=stmt.executeQuery("select * from emp765");
con.close();
}
}
ResultSetMetaData Interface
The metadata means data about data i.e. we can get further information from the data.
If you have to get metadata of a table like total number of column, column name, column type etc. ,
ResultSetMetaData interface is useful because it provides methods to get metadata from the ResultSet object.
Method Description
public int getColumnCount()throws SQLException it returns the total number of columns in
the ResultSet object.
public String getColumnName(int index)throws it returns the column name of the specified
SQLException column index.
public String getColumnTypeName(int index)throws it returns the column type name for the
SQLException specified index.
public String getTableName(int index)throws it returns the table name for the specified
SQLException column index.
import java.sql.*;
class Rsmd
{
public static void main(String args[])
{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
con.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}
The java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for batch processing.
Fast Performance
Method Description
import java.sql.*;
class FetchRecords
{
public static void main(String args[])throws Exception
{
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();
stmt.addBatch("insert into user420 values(190,'abhi',40000)");
stmt.addBatch("insert into user420 values(191,'umesh',50000)");
con.commit();
con.close();
}
}
If you see the table user420, two records has been added.
In JDBC, Statements are used to send SQL commands to the database and receive data from the database.
There are various methods provided by JDBC statements such as execute(), executeUpdate(), executeQuery,
etc. which helps you to interact with the database.
Statements Explanation
Statement Statement is the factory for resultset. It is used for general purpose access to the
database. It executes a static SQL query at runtime.
PreparedStatement The PreparedStatement is used when we need to provide input parameters to the
query at runtime.
CallableStatement CallableStatement is used when we need to access the database stored
procedures. It can also accept runtime parameters.
o The PreparedStatement performs faster as compare to Statement because the Statement needs to be
compiled everytime we run the code whereas the PreparedStatement compiled once and then execute
only on runtime.
o PreparedStatement can execute Parameterized query whereas Statement can only run static queries.
o The query used in PreparedStatement is appeared to be similar every time. Therefore, the database can
reuse the previous access plan whereas, Statement inline the parameters into the String, therefore, the
query doesn't appear to be same everytime which prevents cache reusage.
o PreparedStatement can prevent SQL Injection attacks.
Type Description