Updated Module 5
Updated Module 5
JDBC Objects: The Concept of JDBC; JDBC Driver Types; JDBC Packages; A Brief Overview of the
JDBC process; Database Connection; Associating the JDBC/ODBC Bridge with the Database;
Statement Objects; ResultSet; Transaction Processing; Metadata, Data types; Exceptions.
JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query
with the database, and processing the results.
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.
Before JDBC, ODBC API was the database API to connect and execute the query with the database.
But ODBC API uses ODBC driver that 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 which is platform independent).
It is important to understand why we need Java Database connectivity. Java applications are required to
connect with the database. Java applications are written in Java programming language, but the
database only understands Structured Query Language (SQL). To establish a connection between Java
application and database, JDBC is used. JDBC contains a set of interfaces and classes which helps to
connect Java applications to the database.
We can use JDBC API to handle database using Java program and can perform the following activities:
Types of JDBC
JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine rather than the server) that
translate requests from Java programs into a protocol understood by the DBMS. These drivers are
software components that implement the interfaces in the JDBC API, allowing Java applications to
interact with a database. Sun Microsystems (now Oracle) defines four types of JDBC drivers, which are
outlined below:
Type-1 driver or 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. Type-1 driver is also
called Universal driver because it can be used to connect to any of the databases.
Advantages
Disadvantages
As a common driver is used in order to interact with different databases, the data transferred through
this driver is not so secured.
The ODBC bridge driver is needed to be installed in individual client machines.
Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.
The Native API driver uses the client -side libraries of the database. This driver converts JDBC method
calls into native calls of the database API. In order to interact with different database, this driver needs
their local API, that’s why data transfer is much more secure as compared to type-1 driver. This driver
is not fully written in Java that is why it is also called Partially Java driver.
Advantage
Native-API driver gives better performance than JDBC-ODBC bridge driver. More secure compared to
the type-1 driver.
Disadvantages
Driver needs to be installed separately in individual client machines
The Vendor client library needs to be installed on client machine.
Type-2 driver isn’t written in java, that’s why it isn’t a portable driver
It is a database dependent driver.
3. Network Protocol Driver – Type 3 Driver (Fully Java Driver)
The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or
indirectly into the vendor-specific database protocol. Here all the database connectivity drivers are
present in a single server, hence no need of individual client-side installation.
Advantages
Type-3 drivers are fully written in Java, hence they are portable drivers.
No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.
Switch facility to switch over from one database to another database.
Disadvantages
Network support is required on client machine.
Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to
be done in the middle tier.
Does not require any native library and Middleware server, so no client-side or server-side installation.
It is fully written in Java language, hence they are portable drivers.
Disadvantage
If the database changes, a new driver may be needed.
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is
type-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.
JDBC Components
There are generally 4 main components of JDBC through which it can interact with a database. They
are as mentioned below:
1. JDBC API
It provides various methods and interfaces for easy communication with the database. It includes two
key packages
JDBC Packages
java.sql: This package, is the part of Java Standard Edition (Java SE) , which contains the core
interfaces and classes for accessing and processing data in relational databases. It also provides
essential functionalities like establishing connections, executing queries, and handling result sets
javax.sql: This package is the part of Java Enterprise Edition (Java EE) , which extends the capabilities
of java.sql by offering additional features like connection pooling, statement pooling, and data source
management.
Database Connection and Associating the JDBC/ODBC Bridge with the Database
JDBC Overview
Java Database Connectivity (JDBC) is an API that provides methods for connecting to and interacting
with databases. It serves as a bridge between Java applications and various database systems.
JDBC/ODBC Bridge
The JDBC/ODBC Bridge (historically known as the JDBC-ODBC Bridge) was developed to allow
Java applications to connect to databases through ODBC drivers. ODBC (Open Database Connectivity)
is a standard API for accessing database management systems.
package jdbc_connect;
import java.sql.*;
package com.mysql;
import java.sql.*;
try {
// Register JDBC driver (not needed for newer versions of JDBC)
// Class.forName("com.mysql.jdbc.Driver");
// Establish connection
Connection connection = DriverManager.getConnection(url, username, password);
// Create a statement
Statement statement = connection.createStatement();
// Close resources
rs.close();
st.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
o/p
package com.mysql;
import java.sql.*;
try {
Connection connection = DriverManager.getConnection(url, username, password);
// Set parameters
preparedStatement.setString(1, "Bru Coffee");
preparedStatement.setString(2, "1200");
// Close resources
preparedStatement.close();
connection.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
o/p
Use DriverManager.getConnection()
Provide connection URL, username, and password
Creates a Connection object
Options include:
4. Execute Query
5.Process Results
Close ResultSet
Close Statement
Close Connection
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
// Process results
}
} catch (SQLException e) {
e.printStackTrace();
}
Read all the existing records from the table coffee which is from the database test and insert a
new coffee product into it
/*
The following MySQL commands have to be executed in MySQL before executing the following
JDBC process.
use test;
package com.mysql;
import java.sql.*;
import java.util.Properties;
// inserting records
String query1 = "insert into coffee (coffee_name, price) values ('Tajmahal', 950)";
// Inserting record
stmt.execute(query1);
stmt.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
o/p
Metadata in JDBC refers to data that describes the structure and characteristics of a database. It
provides information about the database itself rather than the actual data stored within it. JDBC (Java
Database Connectivity) offers several metadata interfaces that allow you to programmatically discover
information about database objects.
DatabaseMetadataExample
package com.mysql;
import java.sql.*;
import java.util.Properties;
try
{
//
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test",
"root",
""
);
if (con != null)
{ System.out.println("Successfully connected to MySQL database test");
}
DatabaseMetaData dbmd = con.getMetaData();
System.out.println("Database: " + dbmd.getDatabaseProductName());
System.out.println("Version: " + dbmd.getDatabaseProductVersion());
System.out.println("Driver: " + dbmd.getDriverName());
System.out.println("Driver Version: " + dbmd.getDriverVersion());
// List all tables in the database
System.out.println("\nTables in database:");
ResultSet tables = dbmd.getTables(null, null, "%", new String[]{"TABLE"});
while (tables.next()) {
System.out.println(tables.getString("TABLE_NAME"));
}
o/p
Tables in database:
Employee
Employee1
emp
emp1
emp2
emp3
mail
tutorials_tbl
package com.mysql;
import java.sql.*;
public class ResultSetMetaDataExample {
public static void main(String[] args) {
// Register the JDBC driver - needs to be caught or declared
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
while (rs.next()) {
for (int i = 1; i <= columnCount; i++) {
System.out.print(rs.getString(i) + "\t");
}
System.out.println();
}
}
catch (ClassNotFoundException e) {
System.out.println("MySQL JDBC Driver not found!");
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
o/p
Total columns: 3
Column 1 Information:
Name: id
Type: INT
Size: 10
Nullable: false
Column 2 Information:
Name: coffee_name
Type: VARCHAR
Size: 100
Nullable: false
Column 3 Information:
Name: price
Type: INT
Size: 10
Nullable: true
Query Results:
id coffee_name price
102 Royal 950
103 Diamond 890
267 Delux 950
268 Delux 950
269 Delux 950
270 Tata Coffine 1200
271 Bru Coffee 1200