0% found this document useful (0 votes)
15 views25 pages

Advance Java Programming - UNIT 2 JDBC

Uploaded by

xyzp9702
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views25 pages

Advance Java Programming - UNIT 2 JDBC

Uploaded by

xyzp9702
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Advanced JAVA Programming

GOVERNMENT POLYTECHINC
HIMATNAGAR

DEPARTMENT OF INFORMATION TECHNOLOGY

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.

Why use JDBC


Before JDBC, ODBC API was the database API to connect and execute 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).

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:

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)

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

1) JDBC-ODBC bridge 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.

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.

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

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.

3) Network Protocol driver


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

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

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.

5 Steps to connect to the database in java


There are 5 steps to connect any java application with the database in java using JDBC. They are as
follows:

o Register the driver class


o Creating connection
o Creating statement
o Executing queries
o Closing 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

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Example to register the OracleDriver class


Class.forName("org.apache.derby.jdbc.ClientDriver");

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

Example to establish connection with the Oracle database


Connection con=DriverManager.getConnection(
"jdbc:derby://localhost:1527/Demo","root","root");

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

Example to create the statement object


Statement stmt=con.createStatement();

4) 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

Example to execute query


ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically. The close() method
of Connection interface is used to close the connection.

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Syntax of close() method


public void close()throws SQLException

Example to close connection


con.close();

Example to connect to the derby database in java


For connecting java application with the derby database, you need to follow 5 steps to perform database
connectivity.

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.

1. create database Demo;


2. use Demo;
3. create table emp(id int(10),name varchar(40),age int(3));

Example to Connect Java Application with derby database

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");

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

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 ().

Useful methods of Driver Manager class

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.

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

By default, connection commits the changes after executing queries.

Commonly used methods of Connection interface:


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.

Commonly used methods of Statement interface:


The important methods of Statement interface are as follows:

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.

4) public int[] executeBatch(): is used to execute batch of commands.

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Example of Statement interface that inserts the record


package democonnection;
import java.sql.*;
public class CreateTable {

public static void main(String[] args) {


try

Class.forName("org.apache.derby.jdbc.ClientDriver");

Connection conn=DriverManager.getConnection("jdbc:derby://localhost:1527/Demo", "root", "root");

Statement st=conn.createStatement();

int rs=st.executeUpdate("insert into student values(1,'A')");

System.out.println("Record Inserted...");

catch(Exception e)

System.out.println("Error is "+e.toString());

}
}
}

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Example of Statement interface that Delete the record


import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.Statement;

public class DeleteDtata {

public static void main(String[] args) {

try

Class.forName("org.apache.derby.jdbc.ClientDriver");

Connection conn=DriverManager.getConnection("jdbc:derby://localhost:1527/Demo", "root",


"root");

Statement st=conn.createStatement();

int rs=st.executeUpdate("delete from student where roll =1");

System.out.println("Record Deleted...");

catch(Exception e)

System.out.println("Error is "+e.toString());

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Example of Statement interface that View the record


package jdbcapplication;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

public class ViewData {

public static void main(String[] args) {

try

Class.forName("org.apache.derby.jdbc.ClientDriver");

Connection conn=DriverManager.getConnection("jdbc:derby://localhost:1527/Demo", "root",


"root");

Statement st=conn.createStatement();

ResultSet rs=st.executeQuery("select * from student");

while (rs.next()) {

System.out.println(rs.getInt(1)+" "+rs.getString(2));

catch(Exception e)

System.out.println("Error is "+e.toString());

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Example of Statement interface that Update the record

package jdbcapplication;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.Statement;

public class UpdatedData {

public static void main(String[] args) {

try

Class.forName("org.apache.derby.jdbc.ClientDriver");

Connection conn=DriverManager.getConnection("jdbc:derby://localhost:1527/Demo", "root",


"root");

Statement st=conn.createStatement();

int rs=st.executeUpdate("UPDATE student SET name='A' where roll=1");

System.out.println("Record Updated...");

catch(Exception e)

System.out.println("Error is "+e.toString());

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

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:

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,

ResultSet.CONCUR_UPDATABLE);

Commonly used methods of ResultSet interface


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 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.

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

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:

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 once.

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 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.

public ResultSet executeQuery() executes the select query. It returns an instance of


ResultSet.

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Example of PreparedStatement interface that inserts the record


import java.sql.*;

public class InsertDataP {

public static void main(String[] args) {

try

Class.forName("org.apache.derby.jdbc.ClientDriver");

Connection conn=DriverManager.getConnection("jdbc:derby://localhost:1527/Demo","root", "root");

PreparedStatement st=conn.prepareStatement("insert into student values(?,?)");

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());

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Example of PreparedStatement interface that Delete the record


package jdbcapplication;

import java.sql.*;

public class DeleteDataP {

public static void main(String[] args) {

try

Class.forName("org.apache.derby.jdbc.ClientDriver");

Connection conn=DriverManager.getConnection("jdbc:derby://localhost:1527/Demo","root", "root");

PreparedStatement pst=conn.prepareStatement("delete from student where roll=? or name=?");

pst.setString(2,"C");

pst.setInt(1, 2);

int i=pst.executeUpdate();

System.out.println("Recored Deleted ..."+i);

catch(Exception e)

System.out.println("Error is "+e.toString());

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Example of PreparedStatement interface that View the record

package jdbcapplication;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class ViewDataP {

public static void main(String[] args) {


try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection conn=DriverManager.getConnection("jdbc:derby://localhost:1527/Demo", "root",
"root");
PreparedStatement pst=conn.prepareStatement("select * from student");
ResultSet rs=pst.executeQuery();

while (rs.next()) {
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
}
catch(Exception e)
{
System.out.println("Error is "+e.toString());
}
}
}

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Example of PreparedStatement interface that Update the record

package jdbcapplication;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class ViewDataP {

public static void main(String[] args) {


try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection conn=DriverManager.getConnection("jdbc:derby://localhost:1527/Demo", "root",
"root");
PreparedStatement pst=conn.prepareStatement("select * from student");
ResultSet rs=pst.executeQuery();

while (rs.next()) {
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
}
catch(Exception e)
{
System.out.println("Error is "+e.toString());
}
}
}

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

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 Management


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.

Simple example of transaction management in jdbc using Statement

Let's see the simple example of transaction management using Statement.

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);

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

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.

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

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.

Advantages of Hibernate Framework

Following are the advantages of hibernate framework:

1) Open Source and Lightweight

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.

3) Database Independent Query

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.

4) Automatic Table Creation

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.

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

5) Simplifies Complex Join

Fetching data from multiple tables is easy in hibernate framework.

6) Provides Query Statistics and Database Status

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.

The Hibernate architecture is categorized in four layers.

o Java application layer


o Hibernate framework layer
o Backhand api layer
o Database layer

Let's see the diagram of hibernate architecture:

This is the high level architecture of Hibernate with mapping file and configuration file.

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

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).

Elements of Hibernate Architecture


For creating the first hibernate application, we must know the elements of Hibernate architecture. They are
as follows:

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.

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

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.

Prepared By: Mr. Nitin K. Kanzariya

You might also like