Java Database Connectivity (JDBC)
What is JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent
connectivity between the Java programming language and a wide range of databases.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with
database usage.
Making a connection to a database.
Creating SQL or MySQL statements.
Executing SQL or MySQL queries in the database.
Viewing & Modifying the resulting records.
Applications of JDBC
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable
access to an underlying database. Java can be used to write different types of executables, such as −
Java Applications
Java Applets
Java Servlets
Java ServerPages (JSPs)
Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database, and take advantage of the
stored data.
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 −
JDBC API − This provides the application-to-JDBC Manager connection.
JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.
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 −
Common JDBC Components
The JDBC API provides the following interfaces and classes −
DriverManager − This class manages a list of database drivers. Matches connection requests from the
java application with the proper database driver using communication sub protocol. The first driver that
recognizes a certain subprotocol under JDBC will be used to establish a database Connection.
Driver − This interface handles the communications with the database server. You will interact directly
with Driver objects very rarely. Instead, you use DriverManager objects, which manages objects of this
type. It also abstracts the details associated with working with Driver objects.
Connection − This interface with all methods for contacting a database. The connection object
represents communication context, i.e., all communication with database is through connection object
only.
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.
Why Should We Use JDBC
Before JDBC, ODBC API was the database API to connect and execute the query with the database. But,
ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That is
why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language).
We can use JDBC API to handle database using Java program and can perform the following activities:
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.
What is API
API (Application programming interface) is a document that contains a description of all the features of a
product or software. It represents classes and interfaces that software programs can follow to communicate with
each other. An API can be created for applications, libraries, operating systems, etc.
What is JDBC Driver?
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 [Link] 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 [Link] interface in their database driver.
JDBC Drivers Types
JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in
which Java operates. Sun has divided the implementation types into four categories, Types 1, 2, 3, and 4,
which is explained below −
Type 1 − JDBC-ODBC Bridge Driver
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine. Using
ODBC, requires configuring on your system a Data Source Name (DSN) that represents the target database.
When Java first came out, this was a useful driver because most databases only supported ODBC access but
now this type of driver is recommended only for experimental use or when no other alternative is available.
The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.
Type 2 − JDBC-Native API
In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are unique to the
database. These drivers are typically provided by the database vendors and used in the same manner as the
JDBC-ODBC Bridge. The vendor-specific driver must be installed on each client machine.
If we change the Database, we have to change the native API, as it is specific to a database and they are mostly
obsolete now, but you may realize some speed increase with a Type 2 driver, because it eliminates ODBC's
overhead.
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
Type 3 − JDBC-Net pure Java
In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use standard network
sockets to communicate with a middleware application server. The socket information is then translated by the
middleware application server into the call format required by the DBMS, and forwarded to the database
server.
This kind of driver is extremely flexible, since it requires no code installed on the client and a single driver can
actually provide
access to
multiple
databases.
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.
Type 4 − 100% Pure Java
In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database through socket
connection. This is the highest performance driver available for the database and is usually provided by the
vendor itself.
This kind of driver is extremely flexible, you don't need to install special software on the client or server.
Further, these drivers can be downloaded dynamically.
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.
Which Driver should be Used?
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.
SQL
Structured Query Language (SQL) is a standardized language that allows you to perform operations on a
database, such as creating entries, reading content, updating content, and deleting entries.
SQL is supported by almost any database you will likely use, and it allows you to write database code
independently of the underlying database.
This chapter gives an overview of SQL, which is a prerequisite to understand JDBC concepts. After going
through this chapter, you will be able to Create, Create, Read, Update, and Delete (often referred to
as CRUD operations) data from a database.
For a detailed understanding on SQL, you can read our MySQL Tutorial.
Create Database
The CREATE DATABASE statement is used for creating a new database. The syntax is −
SQL> CREATE DATABASE DATABASE_NAME;
Example
The following SQL statement creates a Database named EMP −
SQL> CREATE DATABASE EMP;
Drop Database
The DROP DATABASE statement is used for deleting an existing database. The syntax is −
SQL> DROP DATABASE DATABASE_NAME;
Note − To create or drop a database you should have administrator privilege on your database server. Be
careful, deleting a database would loss all the data stored in the database.
Create Table
The CREATE TABLE statement is used for creating a new table. The syntax is −
SQL> CREATE TABLE table_name
(
column_name column_data_type,
column_name column_data_type,
column_name column_data_type
...
);
Example
The following SQL statement creates a table named Employees with four columns −
SQL> CREATE TABLE Employees
(
id INT NOT NULL,
age INT NOT NULL,
first VARCHAR(255),
last VARCHAR(255),
PRIMARY KEY ( id )
);
Drop Table
The DROP TABLE statement is used for deleting an existing table. The syntax is −
SQL> DROP TABLE table_name;
Example
The following SQL statement deletes a table named Employees −
SQL> DROP TABLE Employees;
INSERT Data
The syntax for INSERT, looks similar to the following, where column1, column2, and so on represents the
new data to appear in the respective columns −
SQL> INSERT INTO table_name VALUES (column1, column2, ...);
Example
The following SQL INSERT statement inserts a new row in the Employees database created earlier −
SQL> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
SELECT Data
The SELECT statement is used to retrieve data from a database. The syntax for SELECT is −
SQL> SELECT column_name, column_name, ...
FROM table_name
WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the
BETWEEN and LIKE operators.
Example
The following SQL statement selects the age, first and last columns from the Employees table, where id
column is 100 −
SQL> SELECT first, last, age
FROM Employees
WHERE id = 100;
The following SQL statement selects the age, first and last columns from the Employees table
where first column contains Zara −
SQL> SELECT first, last, age
FROM Employees
WHERE first LIKE '%Zara%';
UPDATE Data
The UPDATE statement is used to update data. The syntax for UPDATE is −
SQL> UPDATE table_name
SET column_name = value, column_name = value, ...
WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the
BETWEEN and LIKE operators.
Example
The following SQL UPDATE statement changes the age column of the employee whose id is 100 −
SQL> UPDATE Employees SET age=20 WHERE id=100;
DELETE Data
The DELETE statement is used to delete data from tables. The syntax for DELETE is −
SQL> DELETE FROM table_name WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the
BETWEEN and LIKE operators.
Example
The following SQL DELETE statement deletes the record of the employee whose id is 100 −
SQL> DELETE FROM Employees WHERE id=100;
Java Database Connectivity with 5 Steps:
There are 5 steps to connect any java application with the database using JDBC. These
steps are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection
1) Register the driver class
The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.
Syntax of forName() method
public static void forName(String className)throws ClassNotFoundException
Example to register the OracleDriver class
Here, Java program is loading oracle driver to esteblish database connection.
[Link]("[Link]");
2) Create the connection object
The getConnection() method of DriverManager class is used to establish connection with the database.
Syntax of getConnection() method
public static Connection getConnection(String url)throws SQLException
public static Connection getConnection(String url,String name,String password) throws SQLException
3) Create the Statement object
The createStatement() method of Connection interface is used to create statement. The
object of statement is responsible to execute queries with the database.
Syntax of createStatement() method
public Statement createStatement()throws SQLException
4) Example to create the statement object
Statement stmt=[Link]();
5) Execute the query
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.
Syntax of executeQuery() method
public ResultSet executeQuery(String sql)throws SQLException
5) Close the connection object
By closing connection object statement and ResultSet will be closed automatically. The close() method of Connec
interface is used to close the connection.
Syntax of close() method
public void close()throws SQLException
Example to close connection
[Link]();
Java Database Connectivity with MySQL
To connect Java application with the MySQL database, we need to follow 5 following steps.
In this example we are using MySql as the database. So we need to know following informations for the mysql
database:
1. Driver class: The driver class for the mysql database is [Link].
2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database, localhost is the
server name on which mysql is running, we may also use IP address, 3306 is the port number and sonoo
is the database name. We may use any database, in such case, we need to replace the sonoo with our
database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of installing the mysql database. In this
example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating table, we need to create database first.
1. create database sonoo;
2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));
Example to Connect Java Application with mysql database
In this example, sonoo is the database name, root is the username and password both.
import [Link].*;
class MysqlCon{
public static void main(String args[]){
try{
[Link]("[Link]");
Connection con=[Link](
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
Statement stmt=[Link]();
ResultSet rs=[Link]("select * from emp");
while([Link]())
[Link]([Link](1)+" "+[Link](2)+" "+[Link](3));
[Link]();
}catch(Exception e){ [Link](e);}
}
}
The above example will fetch all the records of emp table.
To connect java application with the mysql database, [Link] file is required to be loaded.
download the jar file [Link]
Two ways to load the jar file:
1. Paste the [Link] file in jre/lib/ext folder
2. Set classpath
1) Paste the [Link] file in JRE/lib/ext folder:
Download the [Link] file. Go to jre/lib/ext folder and paste the jar file here.
2) Set classpath:
There are two ways to set the classpath:
o temporary
o permanent
How to set the temporary classpath
open command prompt and write:
C:>set classpath=c:\folder\[Link];.;
How to set the permanent classpath
Go to environment variable then click on new tab. In variable name write classpath and in variable value paste
the path to the [Link] file by appending [Link];.; as C:\folder\mysql-connector-java-
[Link];.;
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query.
Let's see the example of parameterized query:
String sql="insert into emp values(?,?,?)";
As you can see, we are passing parameter (?) for the values. Its value will be set by calling the setter methods of
PreparedStatement.
Why use PreparedStatement?
Improves performance: The performance of the application will be faster if you use PreparedStatement
interface because query is compiled only [Link]
How to get the instance of PreparedStatement?
The prepareStatement() method of Connection interface is used to return the object of PreparedStatement.
Syntax:
public PreparedStatement prepareStatement(String query)throws SQLException{}
Methods of PreparedStatement interface
The important methods of PreparedStatement interface are given below:
Method Description
public void setInt(int paramIndex, int value) sets the integer value to the given parameter index.
public void setString(int paramIndex, String sets the String value to the given parameter index.
value)
public void setFloat(int paramIndex, float sets the float value to the given parameter index.
value)
public void setDouble(int paramIndex, double sets the double value to the given parameter index.
value)
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.
Example of PreparedStatement interface that inserts the record
First of all create table as given below:
create table emp(id number(10),name varchar2(50));
Now insert records in this table by the code given below:
import [Link].*;
class InsertPrepared{
public static void main(String args[]){
try{
[Link]("[Link]");
Connection con=[Link]("jdbc:mysql://localhost:3306/sonoo","root","root");
PreparedStatement stmt=[Link]("insert into Emp values(?,?)");
[Link](1,101);//1 specifies the first parameter in the query
[Link](2,"Ratan");
int i=[Link]();
[Link](i+" records inserted");
[Link]();
}catch(Exception e){ [Link](e);}
}
}
Example of PreparedStatement interface that updates the record
PreparedStatement stmt=[Link]("update emp set name=? where id=?");
[Link](1,"Sonoo");//1 specifies the first parameter in the query i.e. name
[Link](2,101);
int i=[Link]();
[Link](i+" records updated");
Example of PreparedStatement interface that deletes the record
int i=stmt. PreparedStatement stmt=[Link]("delete from emp where id=?");
[Link](1,101);
executeUpdate();
[Link](i+" records deleted");
Example of PreparedStatement interface that retrieve the records of a table
PreparedStatement stmt=[Link]("select * from emp");
ResultSet rs=[Link]();
while([Link]()){
[Link]([Link](1)+" "+[Link](2));
}
Transaction Management in JDBC
Transaction represents a single unit of work.
The ACID properties describes the transaction management well. ACID stands for Atomicity, Consistency,
isolation and durability.
Atomicity means either all successful or none.
Consistency ensures bringing the database from one consistent state to another consistent state.
Isolation ensures that transaction is isolated from other transaction.
Durability means once a transaction has been committed, it will remain so, even in the event of errors, power
loss etc.
Advantage of Transaction Mangaement
Fast performance It makes the performance fast because database is hit at the time of commit.
In JDBC, Connection interface provides methods to manage transaction.
Method Description
void setAutoCommit(boolean status) It is true bydefault means each transaction is committed bydefault.
void commit() commits the transaction.
void rollback() cancels the transaction.
If your JDBC Connection is in auto-commit mode, which it is by default, then every SQL statement is
committed to the database upon its completion.
That may be fine for simple applications, but there are three reasons why you may want to turn off the auto-
commit and manage your own transactions −
To increase performance.
To maintain the integrity of business processes.
To use distributed transactions.
Transactions enable you to control if, and when, changes are applied to the database. It treats a single SQL
statement or a group of SQL statements as one logical unit, and if any statement fails, the whole transaction
fails.
To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default,
use the Connection object's setAutoCommit() method. If you pass a boolean false to setAutoCommit( ), you
turn off auto-commit. You can pass a boolean true to turn it back on again.
For example, if you have a Connection object named conn, code the following to turn off auto-commit −
[Link](false);
Commit & Rollback
Once you are done with your changes and you want to commit the changes then call commit() method on
connection object as follows −
[Link]( );
Otherwise, to roll back updates to the database made using the Connection named conn, use the following code
−
[Link]( );
The following example illustrates the use of a commit and rollback object −
try{
//Assume a valid connection object conn
[Link](false);
Statement stmt = [Link]();
String SQL = "INSERT INTO Employees " +" VALUES (106, 20, 'Rita', 'Tez')";
[Link](SQL);
//Submit a malformed SQL statement that breaks
String SQL = "INSERTED IN Employees " + " VALUES (107, 22, 'Sita', 'Singh')";
[Link](SQL);
// If there is no error.
[Link]();
}
catch(SQLException se)
{
// If there is any error.
[Link]();
}
In this case, none of the above INSERT statement would success and everything would be rolled back.
Using Savepoints
The new JDBC 3.0 Savepoint interface gives you the additional transactional control. Most modern DBMS,
support savepoints within their environments such as Oracle's PL/SQL.
When you set a savepoint you define a logical rollback point within a transaction. If an error occurs past a
savepoint, you can use the rollback method to undo either all the changes or only the changes made after the
savepoint.
The Connection object has two new methods that help you manage savepoints −
setSavepoint(String savepointName) − Defines a new savepoint. It also returns a Savepoint object.
releaseSavepoint(Savepoint savepointName) − Deletes a savepoint. Notice that it requires a
Savepoint object as a parameter. This object is usually a savepoint generated by the setSavepoint()
method.
There is one rollback (String savepointName) method, which rolls back work to the specified savepoint.
The following example illustrates the use of a Savepoint object −
try{
//Assume a valid connection object conn
[Link](false);
Statement stmt = [Link]();
//set a Savepoint
Savepoint savepoint1 = [Link]("Savepoint1");
String SQL = "INSERT INTO Employees " + "VALUES (106, 20, 'Rita', 'Tez')";
[Link](SQL);
//Submit a malformed SQL statement that breaks
String SQL = "INSERTED IN Employees " + "VALUES (107, 22, 'Sita', 'Tez')";
[Link](SQL);
// If there is no error, commit the changes.
[Link]();
}
catch(SQLException se)
{
// If there is any error.
[Link](savepoint1);
}
In this case, none of the above INSERT statement would success and everything would be rolled back.
Simple example of transaction management in jdbc using Statement
Let's see the simple example of transaction management using Statement.
import [Link].*;
class FetchRecords{
public static void main(String args[])throws Exception{
[Link]("[Link]");
Connection con=[Link]("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
[Link](false);
Statement stmt=[Link]();
[Link]("insert into user420 values(190,'abhi',40000)");
[Link]("insert into user420 values(191,'umesh',50000)");
[Link]();
[Link]();
}}
If you see the table emp400, you will see that 2 records has been added.
JDBC - Stored Procedure
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.
What is the difference between stored procedures and functions.
The differences between stored procedures and functions are given below:
Stored Procedure Function
is used to perform business logic. is used to perform calculation.
must not have the return type. must have the return type.
may return 0 or more values. may return only one values.
We can call functions from the procedure. Procedure cannot be called from function.
Procedure supports input and output parameters. Function supports only input parameter.
Exception handling using try/catch block can be used Exception handling using try/catch can't be used in
in stored procedures. user defined functions.
The following table provides a summary of each interface's purpose to decide on the interface to use.
Interfaces Recommended Use
Statement Use this for general-purpose access to your database. Useful when you are using
static SQL statements at runtime. The Statement interface cannot accept parameters.
PreparedStatement Use this when you plan to use the SQL statements many times. The
PreparedStatement interface accepts input parameters at runtime.
CallableStatement Use this when you want to access the database stored procedures. The
CallableStatement interface can also accept runtime input parameters.
Three types of parameters exist: IN, OUT, and INOUT. The PreparedStatement object only uses the IN
parameter. The CallableStatement object can use all the three.
Here are the definitions of each −
Parameter Description
IN A parameter whose value is unknown when the SQL statement is created. You bind values
to IN parameters with the setXXX() methods.
OUT A parameter whose value is supplied by the SQL statement it returns. You retrieve values
from theOUT parameters with the getXXX() methods.
INOUT A parameter that provides both input and output values. You bind variables with the
setXXX() methods and retrieve values with the getXXX() methods.
How to get the instance of CallableStatement?
The prepareCall() method of Connection interface returns the instance of CallableStatement.
Syntax is given below:
1. public CallableStatement prepareCall("{ call procedurename(?,?...?)}");
The example to get the instance of CallableStatement is given below:
1. CallableStatement stmt=[Link]("{call myprocedure(?,?)}");
It calls the procedure myprocedure that receives 2 arguments.
Full example to call the stored procedure using JDBC
To call the stored procedure, you need to create it in the database. Here, we are assuming that stored procedure
looks like this.
create or replace procedure "INSERTR"
(id IN NUMBER, name IN VARCHAR2)
is begin
insert into user420 values(id,name);
end;
/
The table structure is given below:
create table user420(id number(10), name varchar2(200));
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 [Link].*;
public class Proc {
public static void main(String[] args) throws Exception{
[Link]("[Link]");
Connection con=[Link]( "jdbc:mysql://localhost:3306/sonoo","root","root");
CallableStatement stmt=[Link]("{call insertR(?,?)}");
[Link](1,1011);
[Link](2,"Amit");
[Link]();
[Link]("success");
}
}
Now check the table in the database, value is inserted in the user420 table.
Example to call the function using JDBC
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.
Let's create the simple function in the database first.
create or replace function sum4 (n1 in number,n2 in number)
return number
is temp number(8);
begin
temp :=n1+n2;
return temp;
end;
/
Now, let's write the simple program to call the function.
import [Link].*;
public class FuncSum {
public static void main(String[] args) throws Exception{
[Link]("[Link]");
Connection con=[Link]( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
CallableStatement stmt=[Link]("{?= call sum4(?,?)}");
[Link](2,10);
[Link](3,43);
[Link](1,[Link]);
[Link]();
[Link]([Link](1));
}
}
Output: 53