Unit 3_JDBC
Unit 3_JDBC
Bhupendra Panchal
4/18/2023 1
Outlines
• JDBC Using Relational Databases: Introduction
• Best Practices for Programming for Databases
• JDBC Drivers for RDBM Systems
• SQL to Java Type Mapping
• Using the java.sql API
• Coding Transactions
• Using the Javax.sql API
• Connection pooling
4/18/2023 2
Topics
• Overview
– JDBC
– Types of Drivers
– API
• Connecting to Databases
• Executing Queries & Retrieving Results
• Advanced Topics
– Prepared Statements
– Connection Pooling
• Assignment
4/18/2023 3
Overview
4/18/2023 4
JDBC: Definition
• JDBC: Java Database Connectivity
– JDBC is a Java API to connect and execute the query with the
database. It is a part of JavaSE (Java Standard Edition).
– It provides a standard library for Java programs to connect to a
database and send it commands using SQL.
– It generalizes common database access functions into a set of
common classes and methods.
4/18/2023 7
JDBC: API
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:
• Connect to the database
• We can use JDBC API to access tabular data stored in any relational database.
• By the help of JDBC API, we can save, update, delete and fetch data from the
database.
• It is like Open Database Connectivity (ODBC) provided by Microsoft.
4/18/2023 8
JDBC: 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.
4/18/2023 9
JDBC: API
• Two main packages java.sql and javax.sql
– Java.sql contains all core classes required for accessing database
(Part of Java 2 SDK, Standard Edition)
– Javax.sql contains optional features in the JDBC 2.0 API
(part of Java 2 SDK, Enterprise Edition)
4/18/2023 10
JDBC: Architecture
• JDBC Consists of two parts:
– JDBC API, a purely Java-based
API
– JDBC Driver Manager, which
communicates with vendor-
specific drivers that perform the
real communication with the
database
4/18/2023 11
JDBC: Architecture
4/18/2023 12
JDBC: Interfaces & Classes
A list of popular interfaces of A list of popular classes of
JDBC API are: JDBC API are:
Driver interface DriverManager class
Connection interface Blob class
Statement interface Clob class
PreparedStatement interface Types class
ResultSet interface
ResultSetMetaData interface
DatabaseMetaData interface
RowSet interface
4/18/2023 13
JDBC: Drivers
• JDBC Driver is a software component that enables java application
to interact with the database.
• JDBC uses drivers to translate generalized JDBC calls into vendor-
specific database calls
4/18/2023 14
JDBC: JDBC-ODBC bridge driver (Type I)
• Type I driver provides mapping between JDBC and access API of a database
– The access API calls the native API of the database to establish communication
• A common Type I driver defines a JDBC to ODBC bridge
– ODBC is the database connectivity for databases
– JDBC driver translates JDBC calls to corresponding ODBC calls
– Thus if ODBC driver exists for a database this bridge can be used to
communicate with the database from a Java application
• Inefficient and narrow solution
– Inefficient, because it goes through multiple layers
– Narrow, since functionality of JDBC code limited to whatever ODBC supports
Driver (Type I)
ODBC API
Native API
Client
Application API Protocol Database Specific Database
Protocol
4/18/2023 15
JDBC: JDBC-ODBC bridge driver (Type I)
• 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.
4/18/2023 16
JDBC: JDBC-ODBC bridge driver (Type I)
Advantages:
1. Easy to use.
2. No need to install separately, since it is provided by Sun
Microsystem so it is part of JDK.
3. Database Independent : can be easily connected to any database
Disadvantages:
1.Performance degraded because JDBC method call is converted into
the ODBC function calls. (Called Snail Driver)
2.The ODBC driver needs to be installed on the client machine.
3. Platform dependent because it is provided by Microsoft (Only for Windows)
4. Supports upto JAVA 1.7 version only.
4/18/2023 17
JDBC:
Native-API driver (partially java driver) (Type II)
• Type II driver communicates directly with native API
– Type II makes calls directly to the native API calls
– More efficient since there is one less layer to contend with
(i.e. no ODBC)
– It is dependent on the existence of a native API for a
database
Driver (Type II)
Native API
Client
Application Database
API Protocol Database Specific
Protocol
4/18/2023 18
JDBC:
Native-API driver (partially java driver) (Type II)
Advantage:
•performance upgraded than JDBC-ODBC bridge driver.
•Portability is more. Can support windows, linux etc.
Disadvantage:
•Database dependent (if you change database, change the driver)
•Platform dependent (if you change platform, change the driver)
4/18/2023 19
•The Vendor client library needs to be installed on client machine.
JDBC
Network Protocol driver (fully java driver) (Type III)
• Type III driver make calls to a middleware component running on
another server
– This communication uses a database independent net protocol
– Middleware server then makes calls to the database using database-
specific protocol
– The program sends JDBC call through the JDBC driver to the middle
tier
– Middle-tier may use Type I or II JDBC driver to communicate with
the database.
Driver (Type III)
Client Middleware
Application Net Protocol Server Database Specific Database
Protocol
4/18/2023 20
JDBC
Network Protocol driver (fully java driver) (Type III)
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.
4/18/2023 21
JDBC
Network Protocol driver (fully java driver) (Type III)
Advantage:
•No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
•Network support is required on client machine.
•Requires database-specific coding to be done in the middle tier.
•Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.
4/18/2023 22
JDBC:
Thin driver (fully java driver) (Type IV)
Client
Application Database Specific Database
Protocol
4/18/2023 23
JDBC:
Thin driver (fully java driver) (Type IV)
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:
• Pure Java Driver so it is platform
independent driver.
• Better performance than all other
drivers because of less conversion.
• No ODBC/ Native library/
middleware software is required at
client side or server side.
Disadvantage:
• Drivers depend on the Database.
4/18/2023 24
Connecting to Database
4/18/2023 25
Java Database Connectivity
There are 5 steps to connect any java application with the database using JDBC.
Driver
Established
Link to DB
Database
4/18/2023 27
1. Driver Manager Class
Register the DriverManager class
• The forName() method of Class is used to register the driver class. This
method is used to dynamically load the driver class.
}
catch(Exception e)
{ System.out.println(e);}
}
}
4/18/2023 29
2. Connection Interface
Create the connection object
• A Connection is a session between a Java application and a database. It
helps to establish a connection with the database.
}
catch(Exception e)
{ System.out.println(e);}
}
}
4/18/2023 31
3. Statement Object
Create the Statement object
Statement stmt=con.createStatement();
Statement: Syntax
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
4/18/2023 36
Executing Queries
DDL (Example)
• Example 2: Update table
Statement statement = connection.createStatement();
String sqlString =
“Insert into Catalog”
+ “(Title, LeadActor, LeadActress, Type, ReleaseDate)”
+ “Values(‘Gone With The Wind’, ‘Clark Gable’, ‘Vivien Liegh’,”
+ “’Romantic’, ‘02/18/2003’ ”
Statement.executeUpdate(sqlString);
– executeUpdate returns a 1 since one row is added
4/18/2023 37
Executing Queries
Data Manipulation Language (DML)
• Data definition language queries use executeQuery
• Syntax
ResultSet executeQuery(String sqlString) throws SQLException
– It returns a ResultSet object which contains the results of the Query
• Example 1: Query a table
Statement statement = connection.createStatement();
String sqlString = “Select Catalog.Title, Catalog.LeadActor, Catalog.LeadActress,” +
“Catalog.Type, Catalog.ReleaseDate From Catalog”;
ResultSet rs = statement.executeQuery(sqlString);
4/18/2023 38
Java Database Connectivity
5) Close the connection object
con.close();
Source Code
4/18/2023 40
Requirement to perform JDBC
1. JDK
2. JAVA IDE such as
– Eclipse IDE, Netbeans etc
– Any text editor such as Notepad, VSCode etc.
3. Database Software such as Oracle 11g/MySQL
4. Download the jar file
– ojdbc14.jar for Oracle
– mysql-connector-java-8.0.22 for MySQL
Java Database Connectivity with Oracle
To connect java application with the oracle database, we need to follow 5
following steps. In this example, we are using Oracle 11g as the database. So we
need to know following information for the oracle database:
4. Password: It is the password given by the user at the time of installing the oracle
database.
5. Create a Table: Before establishing connection, let's first create a table in oracle
database. Following is the SQL query to create a table.
package JDBCDemo;
import java.sql.*;
public class JDBC_Connect {
while(rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Java Database Connectivity with MySQL
package JDBCDemo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBC_Connect_SQL {
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root","root");
//db is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");
while(rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Advanced Topics
4/18/2023 46
SQL to Java Type Mapping
When you retrieve data from a database into an iterator object (see Result
sets) or into a host variable, you must use Java™ types that are compatible
with the SQL types. The following table shows valid conversions from SQL
types to Java types.
SQL type Java type
BIGINT, BIGSERIAL bigint
BOOLEAN boolean
BYTE byte[]
CHAR, CHARACTER String
DATE java.sql.Date
DATETIME java.sql.Timestamp
FLOAT, DOUBLE double
INTEGER, INT int
TEXT String
VARCHAR String
SQL to Java Type Mapping
Let us see with an example for the ’employee’ We can map these employee attributes in SQL
class in java Server tables easily. Let us see how to do that
// salary of an employee
private int salary;
// qualification of an employee
private String qualification;
//.....
}
SQL to Java Type Mapping using java.sql
• The java.sql package provides the API for accessing and processing data
stored in a data source (usually a relational database) using the Java
programming language.
• The java.sql package contains the entire JDBC API that sends SQL
(Structured Query Language) statements to relational databases and retrieves
the results of executing those SQL statements.
• This API includes a framework whereby different drivers can be installed
dynamically to access different data sources.
Connection Pooling
• A JDBC connection pool is a group of reusable connections for a particular
database. Because creating each new physical connection is time consuming,
the server maintains a pool of available connections to increase performance.
When an application requests a connection, it obtains one from the pool.
• Connection pooling is a well-known data access pattern. Its main purpose is to
reduce the overhead involved in performing database connections and
read/write database operations.