Chapter 6 (UNIT 2)
JDBC (Java Database Connetivity)
(Database Connectivity, Type of drivers for connections, Connection Example, CRUD operations
using database, Configurig various type of drivers for java database connectivity, MVC Model for
project development, Sequences, dual Table, Datatype management in Java)
Database Connectivity
JDBC (Java Database Connectivity) is a Java-based API (Application Programming
Interface) that provides a standard interface for connecting Java applications with
relational databases. It allows Java programs to interact with databases, execute SQL
queries, and retrieve or update data.
Key Features of JDBC:
• Database Connectivity: Allows Java applications to connect seamlessly with
multiple relational databases.
• SQL Execution: Supports executing SQL queries, including SELECT, INSERT, UPDATE,
and DELETE operations.
• Result Processing: Enables retrieval and manipulation of data from the database.
• Platform Independence: Works across different database management systems
using JDBC drivers.
Why use JDBC over ODBC
Feature JDBC Architecture ODBC Architecture
Language-
Language
Java-specific API independent (C, C++,
Dependency
etc.)
Platform- Platform-dependent
Platform
independent (works (relies on native OS
Dependency
on any OS with JVM) libraries)
Driver Type Uses JDBC Drivers Uses ODBC Drivers
Faster (direct Java Slower (extra ODBC
Performance
integration) layer)
Recommended for Suitable for non-Java
Usage
Java applications applications
Less secure (relies on
More secure (runs
Security system
inside Java)
configurations)
Steps to Connect a Java Application with a Database
using JDBC
1. Importing Packages
2. Loading JDBC Drivers
3. Opening a Connection to a Database
4. Creating a Statement Object
5. Executing a Query and Returning a Result Set Object
6. Processing the Result Set
7. Closing the Result Set and Statement Objects
8. Closing the Connection
1. Importing Packages
The JDBC API is part of the [Link] package and provides various interfaces, classes, and
exceptions to facilitate database connectivity in Java applications.
import [Link].*; // For standard JDBC operations
import [Link].*; // For handling Decimal and Integer values
The [Link] package contains essential classes and interfaces for database operations.
Interfaces:
CallableStatement, Connection, DatabaseMetaData, Statement, Driver,
PreparedStatement, ResultSet, ResultSetMetaData etc.
Classes:
Date, DriverManager, DriverPropertyInfo, Time, Timestamp, Types
Exceptions:
DataTruncation, SQLException, SQLWarning
2. Loading JDBC Drivers
Before a Java application can interact with a database, it needs to load the appropriate JDBC
driver. The driver acts as a bridge between the Java application and the database.
Methods to Load a JDBC Driver
1. Using [Link]() (Explicit Loading - Pre JDBC 4.0)
[Link]("[Link]");
• This method dynamically loads the driver class into memory.
• It ensures that the driver is registered with DriverManager.
• Commonly used for MySQL, PostgreSQL, Oracle, and SQL Server drivers.
2. Automatic Loading (JDBC 4.0+)
• The driver is loaded automatically when [Link]() is called.
• No need to call [Link]() explicitly
Connection conn = [Link]("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
2. Loading JDBC Driver Contd.
Driver Class Names for Common
Databases
Database JDBC Driver Class
MySQL [Link]
PostgreSQL [Link]
Oracle [Link]
SQL Server [Link]
3. Opening a Connection to a Database
Once the JDBC driver is loaded, the next step is to establish a connection between the Java application and
the database using [Link]().
Connection conn = [Link]("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
Connection URL Format for Different Databases
Each database has its own JDBC connection URL format:
Database JDBC URL Format
MySQL jdbc:mysql://hostname:port/database_name
PostgreSQL jdbc:postgresql://hostname:port/database_name
Oracle jdbc:oracle:thin:@hostname:port:SID
SQL Server jdbc:sqlserver://hostname:port;databaseName=DB_NAME
3. Opening a Connection to a Database
import [Link];
import [Link];
import [Link];
public class DatabaseConnection {
public static void main(String[] args) {
// Database connection details
String url = "jdbc:mysql://localhost:3306/mydatabase"; // JDBC URL
String user = "root"; // Database username
String password = "password"; // Database password
try {
// Establish connection
Connection conn = [Link](url, user, password);
[Link]("Database connected successfully!");
// Close the connection
[Link]();
} catch (SQLException e) {
[Link]("Database connection failed! " + [Link]());
}
}
}
4. Creating a Statement Object
Once a connection is established, the next step is to create a Statement object, which is used to
execute SQL queries SELECT, INSERT, UPDATE, DELETE) against the database.
Types of Statement Objects in JDBC
JDBC provides three types of statements to execute SQL queries:
Statement Type Description Use Case
Statement Used for simple SQL queries without parameters. Best for static queries.
PreparedStatement Precompiled SQL statement with parameters (?). Best for dynamic queries and security.
CallableStatement Used to call stored procedures in the database. Best for executing stored procedures.
We create a Statement object from a Connection using the createStatement() method. Always
close the Statement object after execution to free resources.
Statement stmt = [Link]();
5. Executing a Query and Returning a Result Set Object
Once the Statement object is created, we can use it to execute SQL queries. The result of SELECT
queries is stored in a ResultSet object.
Methods to Execute Queries in JDBC
JDBC provides three methods in the Statement interface to execute SQL commands:
Method Return Type Use Case
executeQuery(String sql) ResultSet Used for SELECT queries (fetching data).
Used for INSERT, UPDATE, DELETE queries
executeUpdate(String sql) int (row count)
(modifying data).
Used for DDL (CREATE, ALTER, DROP) and
execute(String sql) boolean
multiple result sets.
5. Executing a Query and Returning a Result Set Object /CRUD
Operations
Example: Fetching Data from a Database Example: Updating a Record
//Execute SQL query String sql = "UPDATE users SET email='ankita44@[Link]' WHERE id=1";
String sql = "SELECT id, name, email FROM users"; int rowsAffected = [Link](sql);
ResultSet rs = [Link](sql); [Link](rowsAffected + " row(s) updated.");
// Process the ResultSet
while ([Link]())
{
int id = [Link]("id"); // Fetch ID column Example: Creating a table in a database
String name = [Link]("name"); // Fetch Name column
String email = [Link]("email"); // Fetch Email column String sql = "CREATE TABLE Students (" + "ID INT PRIMARY KEY, " + "Name
VARCHAR(50), " + "Age INT)";
[Link]("ID: " + id + ", Name: " + name + ", Email: " boolean result = [Link](sql);
+ email); [Link]("Table Created: " + !result);
}
6. Processing the Result Set
When executing a SELECT query using executeQuery(), the result is stored in a ResultSet object. The
ResultSet represents the data retrieved from the database and allows us to process it row by row.
Navigating Through the ResultSet
The ResultSet cursor starts before the first row. To process the data, we use the .next() method to move
the cursor forward.
Common ResultSet Methods
Method Description
[Link]() Moves the cursor to the next row (returns false when no more rows).
[Link](columnLabel) Retrieves an integer from a column.
[Link](columnLabel) Retrieves a string from a column.
[Link](columnLabel) Retrieves a double value from a column.
[Link](columnLabel) Retrieves a date from a column.
[Link](columnLabel) Retrieves a boolean value from a column.
6. Processing the Result Set
Processing Different Data Types
Example: Handling Various Column Types
if ([Link]()) { // Moves the cursor to the first row
int userId = [Link]("id");
String username = [Link]("username");
double balance = [Link]("balance");
boolean isActive = [Link]("active");
[Link] dob = [Link]("date_of_birth");
[Link]("ID: " + userId + ", Name: " + username + ", Balance: " + balance + ", Active:
" + isActive + ", DOB: " + dob);
}
By default, a ResultSet in JDBC is forward-only, meaning you can only move forward through the
rows. However, if you need to navigate backward, forward, or jump to specific rows, you can create a
scrollable ResultSet using TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE.
6. Processing the Result Set
Creating a Scrollable ResultSet
// Create a scrollable
ResultSet Statement stmt = [Link](ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = [Link]("SELECT id, name, email FROM users");
[Link](); // Move cursor to the last
[Link]("Total Rows: " + [Link]()); // Get total row count
[Link](); // Move cursor to the first row
[Link]("First Row -> ID: " + [Link]("id") + ", Name: " + [Link]("name"));
if ([Link]()) // Move cursor to the previous row (if available)
{ [Link]("Previous Row -> ID: " + [Link]("id") + ", Name: " + [Link]("name")); }
else
{ [Link]("No previous row (Already at first row).");
}
6. Processing the Result Set
Key Cursor Methods for ResultSet
Method Description
[Link]() Moves the cursor to the first row.
[Link]() Moves the cursor to the last row.
[Link]() Moves the cursor to the previous row.
[Link]() Moves the cursor to the next row.
[Link](int rowNumber) Moves the cursor to a specific row.
[Link]() Moves the cursor before the first row.
[Link]() Moves the cursor after the last row.
[Link]() Returns the current row number.
7. Closing the Statement Object ,ResultSet and Connection
• After executing a query and processing the results, always close ResultSet and Statement
before closing the connection.
• After completing database operations, it is essential to close the database connection to
free up resources and prevent potential issues like memory leaks, connection leaks, and
performance degradation.
Why Close ResultSet and Statement? // Close resources
[Link]();
• Prevents memory leaks. [Link]();
• Releases database resources. [Link]
• Avoids exceeding database connection limits.
• Ensures better application performance.
From Java 7 onward, the try-with-resources statement automatically closes JDBC objects when the try
block finishes.
Example
import [Link].*; // Close resources
[Link]();
public class JDBCDemo { [Link]();
public static void main(String[] args) { [Link]();
String url = "jdbc:mysql://localhost:3306/mydatabase"; } catch (SQLException e) {
String user = "root"; [Link]("Database error: " + [Link]());
String password = "password"; } catch (ClassNotFoundException e) {
try { [Link]("JDBC Driver not found!");
// Load JDBC driver }
[Link]("[Link]"); }
// Establish database connection }
Connection conn = [Link](url, user, password);
// Create Statement
Statement stmt = [Link]();
// Execute query
ResultSet rs = [Link]("SELECT * FROM users");
// Process results
while ([Link]()) {
[Link]("ID: " + [Link]("id") + ", Name: " + [Link]("name"));
Types of JDBC Drivers
JDBC Driver is a software component that is used to interact
with the java application with the database. The purpose
of JDBC driver is to convert java calls into database-specific
calls and database specific calls into java calls.
• Type 1
• JDBC-ODBC Bridge
• Type 2
• Native API, partially java driver
• Type 3
• JDBC Network Protocol Driver, partially java
• Type 4
• Native-protocol pure Java driver (100% Java )
[Link]
7744/java-jdbc-driver-b62fd5f6a33a
Type 1 Driver
• This driver is also known as JDBC-ODBC bridge Driver. Internally this Driver will take the support of ODBC Driver to
communicate with the database. Type-1 Driver convert JDBC calls into ODBC calls and ODBC Driver convert ODBC calls
into database-specific calls.
• Using Type-1 Driver for prototyping only and not for production purposes.
Type 2 Driver
• Native API driver converts JDBC calls into database-specific native libraries calls and these calls are directly understood by
the database engine.
• Large database vendors, such as Oracle and IBM, use the Type-2 driver for their enterprise databases.
• Type-2 Drivers aren’t architecturally compatible.
• Type-2 Drivers force developers to write platform-specific code.
Type 3 Driver/ Network Protocol Driver
• For database middle-ware, Type-3 JDBC drivers are pure Java drivers.
• Java application communicates with Network Protocol driver. Network protocol driver converts JDBC calls into middle-wear
specific calls, the middle-wear server communicates with database, middle-wear server convert middle-wear specific calls
into database-specific calls.
Type 3 Driver/ Pure Java Driver
• It is also known as the Thin driver. The thin driver converts JDBC calls into database-specific calls directly.
• Thin driver directly communicates with the database by using database specific native protocol provided by the database
vendor.
• It is a platform, independent Driver.
Which JDBC Drivers should be used?
• If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred
driver type is 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.
Comparison of all types of JDBC Drivers
Thick Driver:
If the database driver requires some extra
component to communicate with database
such type of driver is called the Thick driver.
Example: Type-1,Type-2,Type-3 Driver.
Thin Driver:
If the database driver does not require some
extra component to communicate with
database such type of driver is called the
Thin driver.
Example: Type-4 Driver.
MVC Framework
MVC is a design pattern used in software development to
separate an application into three interconnected
components: Model, View, and Controller. This separation
helps in organizing code, making it easier to manage, test,
and scale.
How MVC Works?
The three parts of MVC are:
[Link]: Defines the structure of the data
[Link]: Handles the user interface and data presentation
[Link]: Updates the model and view based on user input.
MVC Components
Model (M) – Data & Business Logic
• Represents data and business logic.
• Interacts with the database and performs operations like fetching, inserting, updating data.
• Example: A Student class that fetches student records from a database.
View (V) – User Interface (UI)
• Handles UI representation of the data.
• Displays information to users and takes user input.
• Example: An HTML page or a GUI form showing student details.
Controller (C) – Request Handling & Communication
• Acts as a bridge between Model and View.
• Processes user input, calls the Model for data, and updates the View accordingly.
• Example: A Java Servlet or Spring Controller handling requests and responses.
How MVC Works in Project Development?
Step 1: User requests a webpage (View).
Step 2: Controller processes the request.
Step 3: Model fetches required data.
Step 4: Controller sends data to View.
Step 5: View displays the response to the
user.
Example: Student Management System
A Student Management System where a user requests student details, and the application retrieves and displays
them using Spring Boot (Java) and JSP (View).
1. Model (M) – [Link] (Handles Data & Logic): Represents the Student entity and fetches data from the
database.
package [Link];
public class Student {
private int id;
private String name;
private String course;
public Student(int id, String name, String course) {
[Link] = id;
[Link] = name;
[Link] = course;
}
// Getters and Setters
public int getId() { return id; }
public String getName() { return name; }
public String getCourse() { return course; }
}
Example: Student Management System
2. Controller (C) – [Link] (Handles Requests & Logic): Receives the user request
and fetches student data.
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Controller
public class StudentController {
@GetMapping("/student")
public String getStudent(Model model) {
// Simulating fetching student details
Student student = new Student(1, "Abhay", "Computer Science");
// Adding student data to Model
[Link]("student", student);
// Returning view name
return "studentView";
}
}
Example: Student Management System
3. View (V) – [Link] (User Interface): Displays student details.
<%@ page language="java" contentType="text/html;
charset=UTF-8" pageEncoding="UTF-8"%> How the Output is Generated?
<html>
<head> 1️⃣ User requests [Link]
<title>Student Details</title> 2️⃣ [Link] retrieves student details
</head> (id=1, name="Abhay", course="Computer Science").
<body> 3️⃣ Model ([Link]) sends the data to View
<h2>Student Details</h2> ([Link]).
<p><strong>ID:</strong> ${[Link]}</p> 4️⃣ JSP renders the output by replacing ${[Link]},
<p><strong>Name:</strong> ${[Link]}</p> ${[Link]}, and ${[Link]} with actual
<p><strong>Course:</strong> ${[Link]}</p> values.
</body>
</html>
Sequences
Sequence is a set of integers 1, 2, 3, … that are generated and supported by some database systems to
produce unique values on demand. A sequence is a user defined schema bound object that generates a
sequence of numeric values.
Characteristics of Sequences:
• User-Defined Object: A sequence is explicitly created and managed by users.
• Schema-Bound: It exists within a specific database schema.
• Automatic Generation: Produces unique values sequentially (ascending or descending).
• Configurable: Users can define:
• Start value (initial number)
• Increment step (interval between values)
• Min/Max value (optional limits)
• Cycle option (whether to restart after reaching max/min value)
• Independent of Tables: Unlike AUTO_INCREMENT, sequences are separate objects and can be used across
multiple tables.
Sequences Contd.
Syntax
CREATE SEQUENCE sequence_name START WITH initial_value INCREMENT BY increment_value MINVALUE
minimum value MAXVALUE maximum value CYCLE|NOCYCLE ;
Example
CREATE SEQUENCE order_seq START WITH 1000 INCREMENT BY 5 MINVALUE 1000 MAXVALUE
1020 CYCLE;
• START WITH 1000 → First generated value is 1000.
• INCREMENT BY 5 → Each next value increases by 5.
• MINVALUE 1000, MAXVALUE 1020 → The sequence will range from 1000 to 1020.
• CYCLE → When it reaches 1020, it restarts from 1000.
Sequences Contd.
Output (First 5 Calls)
Fetching Next Values Call Number Output (NEXTVAL)
1st Call 1000
SELECT order_seq.NEXTVAL;
2nd Call 1005
3rd Call 1010
4th Call 1015
5th Call 1020
Sequence Cycling (After Reaching MaxValue)
After reaching 1020, since we used CYCLE, the sequence restarts at 1000.
Call Number Output (NEXTVAL)
6th Call 1000
7th Call 1005
Sequences Contd.
Using the Sequence in an Insert Query
INSERT INTO orders (order_id, customer_name) VALUES (order_seq.NEXTVAL, 'Abhay');
order_id customer_name
1000 Abhay
Dual Tables
• DUAL is a special one-row, one-column table present in Oracle databases by default.
• It is owned by SYS (which manages the data dictionary).
• It has a single column named DUMMY, which is of type VARCHAR2(1) and contains the value
'X'.
• Every user can access the DUAL table.
Why is DUAL Used?
DUAL is useful for executing queries that do not require actual tables, such as:
- Performing calculations
- Using functions (e.g., SYSDATE, USER)
- Fetching sequence values
Uses of DUAL Tables
Mathematical Calculation
SELECT 10 * 5 FROM DUAL; 10 * 5
50
Using System Functions
SELECT SYSDATE FROM DUAL; -- Returns current date SYSDATE
08-MAR-25
Fetching a Sequence Value
SELECT order_seq.NEXTVAL FROM DUAL;
NEXTVAL
Why Can’t We DELETE or TRUNCATE the Default DUAL? 1000
DELETE from DUAL (Not Allowed) – Oracle does not allow deleting from the default DUAL table,
but you can delete from a user-created DUAL table.
TRUNCATE DUAL (Not Allowed) – Since the default DUAL table is a system table, TRUNCATE is
not permitted, but it works on a custom DUAL table.
Data Type Management
• The Microsoft JDBC Driver for SQL Server uses the JDBC basic data types to convert the SQL Server
data types to a format that can be understood by the Java programming language, and vice versa.
• The JDBC driver provides support for the JDBC 4.0 API, which includes the SQLXML data type, and
National (Unicode) data types, such as NCHAR, NVARCHAR, LONGNVARCHAR, and NCLOB.
How Java data types map to SQL Server types using JDBC.
Java: String name = "Abhay";
JDBC Converts: String → VARCHAR
SQL Server Stores: 'Abhay' in VARCHAR(50)
Data Type Mapping
A structured table showing the default mappings between SQL Server, JDBC, and Java programming
language data types:
SQL Server Data Type JDBC Data Type Java Data Type
INT INTEGER int
BIGINT BIGINT long
SMALLINT SMALLINT short
TINYINT TINYINT byte
BIT BIT boolean
DECIMAL / NUMERIC DECIMAL BigDecimal
FLOAT DOUBLE double
REAL REAL float
CHAR(n) CHAR String
VARCHAR(n) VARCHAR String
TEXT LONGVARCHAR String
NCHAR(n) NCHAR String
Data Type Mapping Contd.
SQL Server Data Type JDBC Data Type Java Data Type
NVARCHAR(n) NVARCHAR String
NTEXT LONGNVARCHAR String
BINARY(n) BINARY byte[]
VARBINARY(n) VARBINARY byte[]
IMAGE LONGVARBINARY byte[]
DATE DATE [Link]
TIME TIME [Link]
DATETIME / SMALLDATETIME TIMESTAMP [Link]
DATETIME2 TIMESTAMP [Link]
DATETIMEOFFSET TIMESTAMP_WITH_TIMEZONE [Link]
SQLXML SQLXML [Link]
Data Type Mapping Contd.
Handling Date & Time in SQL Server with Java JDBC
Using [Link] with SQL Server
Issue: By default, SQL Server treats [Link] as datetime.
Solution: Set sendTimeAsDatetime=false in the connection properties.
Working with datetimeoffset in SQL Server
SQL Server datetimeoffset stores date, time, and timezone offset.
Working with [Link] Issue in SQL Server 2016+
Issue : SQL Server converts datetime to datetime2 differently, causing mismatches with
[Link].
Solution:
- Use datetime2(3) instead of datetime.
- Convert Timestamp to String before comparison.
- Change database compatibility level to 120 or below.
Questions
• What is JDBC, and why is it used in Java?
• Explain the four types of JDBC drivers and their differences.
• How do you establish a database connection in Java using JDBC?
• What is Connection Pooling in JDBC, and why is it important?
• What is the difference between Statement, PreparedStatement, and CallableStatement?
• How do you perform CRUD operations (Create, Read, Update, Delete) using JDBC?
• Write a Java program to execute a SELECT query using JDBC.
• What is a ResultSet, and what are its different types?
• What is a SEQUENCE in SQL, and why is it used?
• How do you create and use a SEQUENCE in Oracle?
• What is the DUAL table in Oracle, and what is its purpose?
• Why can’t we DELETE or TRUNCATE the default DUAL table?
• What is the default mapping between SQL data types and Java data types in JDBC?
• Why can’t [Link] be used for comparing datetime values in SQL Server 2016 and later?
• What is MVC (Model-View-Controller) in Java?
• How is MVC implemented in a Java web application?
• Explain the roles of Model, View, and Controller in an MVC-based project.