Advance Java Programming - UNIT 2 JDBC
Advance Java Programming - UNIT 2 JDBC
GOVERNMENT POLYTECHINC
HIMATNAGAR
UNIT-2
JDBC
Prepared By: Mr. Nitin K. Kanzariya
Course Title: Advanced JAVA Programming Course Code: 4351603
Unit 2
JDBC Introduction
Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc drivers to
connect with the database.
What is API
API (Application programming interface) is a document that contains 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
JDBC Driver
JDBC Driver is a software component that enables java application to interact with the database. There
are 4 types of JDBC drivers:
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.
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
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.
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 org.apache.derby.jdbc.ClientDriver.
2. Connection URL: The connection URL for the mysql database
is jdbc:derby://localhost:1527/Demo where jdbc is the API, derby is the database, localhost is the
server name on which derby is running, we may also use IP address, 3306 is the port number and
Demo is the database name. We may use any database, in such case, you need to replace the Demo
with your database name.
3. Username: The default username for the derby database is root.
4. Password: Password is given by the user at the time of installing the derby database. In this
example, we are going to use root as the password.
Let's first create a table in the derby database, but before creating table, we need to create database first.
In this example, Demo is the database name, root is the username and password.
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("org.apache.derby.jdbc.ClientDriver ");
Connection con=DriverManager.getConnection( " jdbc:derby://localhost:1527/Demo ","root","root");
//here Demo is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from book");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2));
con.close();
}
catch(Exception e)
{ System.out.println(e);}
}
}
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 driver): is used to deregister the given driver (drop the
driver from the list) with DriverManager.
3) public static Connection getConnection(String url): is used to establish the connection with the
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.
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.
Class.forName("org.apache.derby.jdbc.ClientDriver");
Statement st=conn.createStatement();
System.out.println("Record Inserted...");
catch(Exception e)
System.out.println("Error is "+e.toString());
}
}
}
import java.sql.DriverManager;
import java.sql.Statement;
try
Class.forName("org.apache.derby.jdbc.ClientDriver");
Statement st=conn.createStatement();
System.out.println("Record Deleted...");
catch(Exception e)
System.out.println("Error is "+e.toString());
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try
Class.forName("org.apache.derby.jdbc.ClientDriver");
Statement st=conn.createStatement();
while (rs.next()) {
System.out.println(rs.getInt(1)+" "+rs.getString(2));
catch(Exception e)
System.out.println("Error is "+e.toString());
package jdbcapplication;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
try
Class.forName("org.apache.derby.jdbc.ClientDriver");
Statement st=conn.createStatement();
System.out.println("Record Updated...");
catch(Exception e)
System.out.println("Error is "+e.toString());
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to before
the first row.
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:
ResultSet.CONCUR_UPDATABLE);
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 is used to move the cursor to the specified row number in the
row): 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 is used to return the data of specified column index of the current
columnIndex): row as int.
8) public int getInt(String is used to return the data of specified column name of the current
columnName): row as int.
9) public String getString(int is used to return the data of specified column index of the current
columnIndex): row as String.
10) public String getString(String is used to return the data of specified column name of the current
columnName): row as String.
PreparedStatement interface
The PreparedStatement interface is a sub interface of Statement. It is used to execute parameterized query.
Let's see the example of parameterized query:
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 once.
Method Description
public void setInt(int paramIndex, int sets the integer value to the given parameter index.
value)
public void setString(int paramIndex, sets the String value to the given parameter index.
String value)
public void setFloat(int paramIndex, float sets the float value to the given parameter index.
value)
public void setDouble(int paramIndex, sets the double value to the given parameter index.
double value)
public int executeUpdate() executes the query. It is used for create, drop, insert,
update, delete etc.
try
Class.forName("org.apache.derby.jdbc.ClientDriver");
st.setInt(1,2);
st.setString(2, "B");
int rs=st.executeUpdate();
System.out.println("Record Inserted...");
catch(Exception e)
System.out.println("Error is "+e.toString());
import java.sql.*;
try
Class.forName("org.apache.derby.jdbc.ClientDriver");
pst.setString(2,"C");
pst.setInt(1, 2);
int i=pst.executeUpdate();
catch(Exception e)
System.out.println("Error is "+e.toString());
package jdbcapplication;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
while (rs.next()) {
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
}
catch(Exception e)
{
System.out.println("Error is "+e.toString());
}
}
}
package jdbcapplication;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
while (rs.next()) {
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
}
catch(Exception e)
{
System.out.println("Error is "+e.toString());
}
}
}
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.
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","orac
le");
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");
stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");
con.commit();
con.close();
}}
NOTE: If you see the table emp400, you will see that 2 records has been
added.
Hibernate Framework
Hibernate is a Java framework that simplifies the development of Java application to interact with the
database. It is an open source, lightweight, ORM (Object Relational Mapping) tool. Hibernate implements
the specifications of JPA (Java Persistence API) for data persistence.
ORM Tool
An ORM tool simplifies the data creation, data manipulation and data access. It is a programming
technique that maps the object to the data stored in the database.
The ORM tool internally uses the JDBC API to interact with the database.
Hibernate framework is open source under the LGPL license and lightweight.
2) Fast Performance
The performance of hibernate framework is fast because cache is internally used in hibernate framework.
There are two types of cache in hibernate framework first level cache and second level cache. First level
cache is enabled by default.
HQL (Hibernate Query Language) is the object-oriented version of SQL. It generates the database
independent queries. So you don't need to write database specific queries. Before Hibernate, if database is
changed for the project, we need to change the SQL query as well that leads to the maintenance problem.
Hibernate framework provides the facility to create the tables of the database automatically. So there is no
need to create tables in the database manually.
Hibernate supports Query cache and provide statistics about query and database status.
Hibernate Architecture
The Hibernate architecture includes many objects such as persistent object, session factory, transaction
factory, connection factory, session, transaction etc.
This is the high level architecture of Hibernate with mapping file and configuration file.
Hibernate framework uses many objects such as session factory, session, transaction etc. along with
existing Java API such as JDBC (Java Database Connectivity), JTA (Java Transaction API) and JNDI
(Java Naming Directory Interface).
SessionFactory
The SessionFactory is a factory of session and client of ConnectionProvider. It holds second level cache
(optional) of data. The org.hibernate.SessionFactory interface provides factory method to get the object of
Session.
Session
The session object provides an interface between the application and data stored in the database. It is a
short-lived object and wraps the JDBC connection. It is factory of Transaction, Query and Criteria. It
holds a first-level cache (mandatory) of data. The org.hibernate.Session interface provides methods to
insert, update and delete the object. It also provides factory methods for Transaction, Query and Criteria.
Transaction
The transaction object specifies the atomic unit of work. It is optional. The org.hibernate.Transaction
interface provides methods for transaction management.
ConnectionProvider
It is a factory of JDBC connections. It abstracts the application from DriverManager or DataSource. It is
optional.
TransactionFactory
It is a factory of Transaction. It is optional.