Unit 5: Java Database Connectivity
Java Database Connectivity (JDBC) is an API in Java that enables
interaction with relational databases. It provides methods for querying
and updating data in a database using Java.
JDBC Architecture
JDBC consists of:
1. JDBC API – Defines methods and interfaces for database access.
2. JDBC Driver – Connects Java applications to databases.
3. JDBC Driver Manager – Manages different types of drivers.
4. Database – Stores data.
Steps to Connect to a Database Using
JDBC
1.Load the Driver
Class.forName("com.mysql.cj.jdbc.Driver");
∙ This step is required for older versions of Java. In newer versions, the
driver loads automatically.
2. Establish Connection
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb",
"username", "password");
3.Create a Statement
Statement stmt = con.createStatement();
4.Execute Query
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
System.out.println(rs.getString("name") + " " + rs.getInt("age"));}
5.Close Connection
Types of JDBC Drivers
JDBC (Java Database Connectivity) drivers are used to connect Java
applications to databases. There are four types of JDBC drivers:
1. Type-1: JDBC-ODBC Bridge Driver
● Description: Uses the ODBC (Open Database Connectivity) driver
to connect to the database.
● Advantage: Easy to use, and can connect to almost any database.
● Disadvantage: Performance is slow due to the extra ODBC layer. It
also requires an ODBC driver to be installed on the client machine.
● Example: sun.jdbc.odbc.JdbcOdbcDriver (Deprecated in Java 8)
2. Type-2: Native-API Driver (Partially Java Driver)
● Description: Uses the database vendor's native API (like C or C++
libraries) for connectivity.
● Advantage: Faster than Type-1 since it eliminates the ODBC layer.
● Disadvantage: Requires platform-specific native libraries, making
it non-portable.
● Example: Oracle's OCI driver (oracle.jdbc.driver.OracleDriver)
3. Type-3: Network Protocol Driver (Middleware Driver)
● Description: Uses a middle-tier server that translates JDBC calls
into database-specific calls.
● Advantage: More flexible, can connect to multiple databases.
● Disadvantage: Requires an extra server (middleware), making it
more complex.
● Example: IBM WebSphere ConnectJDBC
4. Type-4: Thin Driver (Pure Java Driver)
● Description: Uses Java to directly communicate with the database,
without requiring native libraries.
● Advantage: High performance, platform-independent, and widely
used.
● Disadvantage: Database-specific; needs a separate driver for each
database.
● Example:
o MySQL: com.mysql.cj.jdbc.Driver
o PostgreSQL: org.postgresql.Driver
o Oracle: oracle.jdbc.OracleDriver
1. Driver Interface (java.sql.Driver)
The Driver interface in JDBC is implemented by database vendors to
provide connectivity to their databases. It acts as a blueprint for all JDBC
drivers.
Key Points:
● It is part of java.sql package.
● Every JDBC driver must implement this interface.
● It is not used directly in most applications; instead, it is managed
by DriverManager.
● The main method in Driver is:
public Connection connect(String url, Properties info) throws
SQLException;
● This method establishes a connection with the database.
Example Implementation (Driver Registration):
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.cj.jdbc.Driver; // MySQL JDBC Driver
public class DriverExample {
public static void main(String[] args) {
try {
DriverManager.registerDriver(new Driver()); // Registers MySQL
Driver
System.out.println("Driver registered successfully!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
2. DriverManager Class (java.sql.DriverManager)
The DriverManager class is responsible for managing JDBC drivers and
establishing database connections.
Key Points:
● It automatically loads available JDBC drivers.
● Provides methods to register and deregister JDBC drivers.
● Connects to the database using a registered driver.
● Common methods
public static Connection getConnection(String url) throws
SQLException;
public static void registerDriver(Driver driver) throws SQLException;
public static void deregisterDriver(Driver driver) throws
SQLException;
Examples:-
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DriverManagerExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "password";
try {
Connection con = DriverManager.getConnection(url, user,
password);
System.out.println("Connected to database!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Connection Interface (java.sql.Connection):-
The Connection interface represents a session between the Java
application and the database.
Key Points:
● Used to execute SQL queries.
● Manages database transactions.
● Provides metadata about the database.
Common methods:
public Statement createStatement() throws SQLException;
public PreparedStatement prepareStatement(String sql) throws
SQLException;
public void close() throws SQLException;
public void setAutoCommit(boolean autoCommit) throws SQLException;
public void commit() throws SQLException;
public void rollback() throws SQLException;
Examples:-
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ConnectionExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "password";
try (Connection con = DriverManager.getConnection(url, user,
password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM
employees")) {
while (rs.next()) {
System.out.println(rs.getInt("id") + " - " +
rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
JDBC Interfaces: Statement, PreparedStatement, and ResultSet:-
In JDBC, these interfaces are used to interact with the database by
executing SQL queries and retrieving results.
1. Statement Interface (java.sql.Statement)
The Statement interface is used to execute static SQL queries.
Key Features:
● Used for executing simple SQL queries without parameters.
● Provides methods to execute SQL queries.
Examples:-
import java.sql.*;
public class StatementExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "password";
try (Connection con = DriverManager.getConnection(url, user,
password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM
employees")) {
while (rs.next()) {
System.out.println(rs.getInt("id") + " - " +
rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Drawbacks of Statement:
● Query compilation happens every time it is executed, leading to
performance overhead.
● Not suitable for dynamic queries with parameters.
2. PreparedStatement Interface (java.sql.PreparedStatement)
The PreparedStatement interface is used for executing parameterized
SQL queries.
Key Features:
● Precompiled SQL statement, making it faster than Statement for
repeated execution.
● Prevents SQL Injection since parameters are set securely.
● Supports dynamic queries with parameters (? placeholders).
Example:-
import java.sql.*;
public class PreparedStatementExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "password";
String sql = "SELECT * FROM employees WHERE department = ?";
try (Connection con = DriverManager.getConnection(url, user,
password);
PreparedStatement pstmt = con.prepareStatement(sql)) {
pstmt.setString(1, "HR"); // Setting parameter value
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt("id") + " - " +
rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Advantages of PreparedStatement over Statement:
✅ Precompiled SQL statements improve performance.
✅ Prevents SQL injection.
✅ Can be reused multiple times with different parameters.
ResultSet Interface (java.sql.ResultSet)
The ResultSet interface represents the result of a database query.
Key Features:
● Provides methods to iterate and retrieve data from the query
result.
● By default, it is forward-only and read-only.
Example:-
import java.sql.*;
public class ResultSetExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "password";
try (Connection con = DriverManager.getConnection(url, user,
password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM
employees")) {
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
double salary = rs.getDouble("salary");
System.out.println("ID: " + id + ", Name: " + name + ", Salary: "
+ salary);
}
} catch (SQLException e) {
e.printStackTrace();
}
}}
JDBC Program for Executing Statements & Processing
ResultSet Using PreparedStatement
This program demonstrates:
1. Connecting to a MySQL database using JDBC.
2. Executing a PreparedStatement to insert and retrieve data.
3. Processing the ResultSet to display data.
Prerequisites
● MySQL Database installed and running.
● A table named employees in the database.
● JDBC Driver for MySQL (mysql-connector-java.jar) added to the
project.
Steps to Follow
1. Load and register the JDBC driver (Not required in Java 8+).
2. Establish a connection using DriverManager.getConnection().
3. Use PreparedStatement to insert and fetch data.
4. Use ResultSet to process query results.
5. Close the database connection.
Example:-
import java.sql.*;
public class JDBCPreparedStatementExample {
public static void main(String[] args) {
// Database connection details
String url = "jdbc:mysql://localhost:3306/mydatabase"; // Change
"mydatabase" to your DB name
String user = "root"; // Change to your MySQL username
String password = "password"; // Change to your MySQL password
// SQL Queries
String insertQuery = "INSERT INTO employees (name, department,
salary) VALUES (?, ?, ?)";
String selectQuery = "SELECT * FROM employees WHERE
department = ?";
try (Connection con = DriverManager.getConnection(url, user,
password)) {
System.out.println("Connected to the database!");
// 1. Insert Data Using PreparedStatement
try (PreparedStatement pstmt =
con.prepareStatement(insertQuery)) {
pstmt.setString(1, "John Doe");
pstmt.setString(2, "IT");
pstmt.setDouble(3, 75000.00);
int rowsInserted = pstmt.executeUpdate();
System.out.println(rowsInserted + " row(s) inserted.");
}
// 2. Fetch and Process Data Using PreparedStatement &
ResultSet
try (PreparedStatement pstmt =
con.prepareStatement(selectQuery)) {
pstmt.setString(1, "IT"); // Fetch employees from the "IT"
department
ResultSet rs = pstmt.executeQuery();
System.out.println("\nEmployees in IT Department:");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String department = rs.getString("department");
double salary = rs.getDouble("salary");
System.out.println("ID: " + id + ", Name: " + name + ",
Salary: $" + salary);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Explanation of the Code
1.Database Connection:
1.Establishes a connection to the MySQL database using
DriverManager.getConnection().
2.Inserting Data using PreparedStatement:
1. Uses ? placeholders for dynamic values.
2. Calls setString() and setDouble() to set values before
execution.
3.Fetching Data using PreparedStatement and ResultSet:
1. Retrieves records from the employees table where
department = 'IT'.
2. Uses ResultSet to iterate over the retrieved records.
4.Processing Results:
1. while (rs.next()) iterates through the ResultSet.
2. Retrieves data using getInt(), getString(), and getDouble().
Database Table Schema
Before running the program, ensure that the employees table exists in
your MySQL database:
CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
department VARCHAR(50),
salary DOUBLE
);
Output:-
Connected to the database!
1 row(s) inserted.
Employees in IT Department:
ID: 1, Name: John Doe, Salary: $75000.0