Java Programming
JDBC & Collections
Framework
A Complete Guide to Database Connectivity & Data Structures in Java
JDBC | CRUD Operations | Collections | Java DSA
Table of Contents
JDBC Overview CRUD Operations
01 06
Definition, Purpose & Architecture Create, Read, Update, Delete with code
JDBC Drivers Collections Hierarchy
02 07
Types 1–4 with use cases Collection framework overview diagram
Connection Steps List Implementations
03 08
Step-by-step database connection ArrayList & LinkedList
Core JDBC APIs Stack & Queue
04 09
DriverManager, Connection, Statement Stack and PriorityQueue
PreparedStatement & ResultSet Map & Set
05 10
Parameterized queries & result navigation HashMap, HashSet and more
Java JDBC & Collections Framework
Part 1: Java Database
Connectivity (JDBC)
What is JDBC? — Definition & Purpose
Definition
JDBC (Java Database Connectivity) is a Java API that enables Java applications to interact with relational databases. It provides a standard interface for
connecting to databases, executing SQL queries, and processing results — regardless of the underlying database engine.
Database Independence SQL Execution Result Processing Transaction Control
Write once, run with any JDBC-
Execute DDL, DML, and stored Navigate through query results with Manage commit/rollback for data
compatible DB (MySQL, Oracle,
procedures from Java code the ResultSet API integrity
PostgreSQL)
Java Database Connectivity API
J D B C
Platform-independent language Any relational DB system Standard connection bridge Part of [Link] package
Java JDBC & Collections Framework
JDBC Architecture
JDBC API DriverManager
Java Application ▶ ▶
([Link] / [Link]) Manages JDBC drivers
▼
Type 1 Type 2 Type 3 Type 4
JDBC-ODBC Bridge Native API Driver Network Protocol Thin Driver
▼ ▼ ▼ ▼
MySQL Oracle MS SQL
PostgreSQL
Database Database Server
Flow: Application → JDBC API → DriverManager → JDBC Driver → Database
Java JDBC & Collections Framework
JDBC Driver Types
Type 1: JDBC-ODBC Bridge Driver Type 2: Native-API Driver
Pros: Pros:
Easy to setup, platform independent in concept Faster than Type 1, uses native DB client library
Cons: Cons:
Slow performance, deprecated in Java 8+, requires ODBC drivers Platform-dependent, requires DB client installed
[Link] [Link] (older)
Type 3: Network Protocol Driver Type 4: Thin Driver (Pure Java)
Pros: Pros:
No client-side installation, flexible, server-side logic ✅ Most popular, pure Java, platform-independent, best performance
Cons: Cons:
Extra network hop, requires middleware server Different driver needed per database vendor
Used in distributed enterprise systems [Link]
Java JDBC & Collections Framework
Steps to Connect to a Database
Step 1: Load the Driver Step 4: Execute Query
1 4
Register the JDBC driver class with DriverManager Execute SQL using executeQuery() or executeUpdate()
[Link]("[Link]"); ResultSet rs = [Link]("SELECT * FROM emp");
Step 2: Establish Connection Step 5: Process Results
2 5
Create a Connection object using getConnection() Iterate over ResultSet to retrieve data
Connection con = [Link](url, user, pass); while([Link]()) { [Link]([Link]("name")); }
Step 3: Create Statement Step 6: Close Resources
3 6
Create a Statement or PreparedStatement object Always close ResultSet, Statement, Connection
Statement stmt = [Link](); [Link](); [Link](); [Link]();
Java JDBC & Collections Framework
DriverManager Class
[Link]
Acts as the entry point to JDBC — manages a list of database drivers and matches connection requests with the right driver.
Method
Method Description
Description
Java
// Getting a Connection using
getConnection(url) Returns Connection for the given DB URL DriverManager
String url = "jdbc:mysql://
localhost:3306/mydb";
getConnection(url, user, pass) Returns Connection with credentials String user = "root";
String pass = "password";
registerDriver(Driver d) Registers a new JDBC driver Connection con =
[Link](url, user,
pass);
setLoginTimeout(seconds) Sets max wait time for a connection
[Link]("Connection
getDrivers() Returns all registered drivers established: " + con);
Java JDBC & Collections Framework
Connection Interface
A Connection object represents a session with a specific database. It is used to create statements, manage transactions, and access database metadata.
createStatement() commit()
Creates a Statement object for SQL execution Commits the current transaction to the database
prepareStatement(sql) rollback()
Creates a PreparedStatement for parameterized SQL Rolls back the current transaction
prepareCall(sql) close()
Creates a CallableStatement for stored procedures Closes the connection and releases DB resources
setAutoCommit(boolean) isClosed()
Enables/disables auto-commit mode for transactions Returns true if the connection has been closed
Java JDBC & Collections Framework
Statement Interface
Statement is used to execute static SQL queries. It does NOT accept parameters. Three execute methods handle different SQL types.
executeQuery(sql) executeUpdate(sql) execute(sql)
Returns: ResultSet Returns: int Returns: boolean
Used for SELECT statements. Returns a ResultSet with Used for INSERT, UPDATE, DELETE. Returns count of
Used for any SQL. Returns true if result is a ResultSet.
rows. rows affected.
Java
// Creating and using a Statement
Connection con = [Link](url, user, pass);
Statement stmt = [Link]();
// SELECT query
ResultSet rs = [Link]("SELECT * FROM students");
// INSERT query
int rows = [Link](
"INSERT INTO students VALUES(101, 'Alice', 'CS')");
[Link]("Rows inserted: " + rows);
[Link](); [Link]();
Java JDBC & Collections Framework
PreparedStatement Interface
PreparedStatement extends Statement and uses parameterized (precompiled) SQL with "?" placeholders. It prevents SQL injection, improves performance for repeated queries,
and handles data type conversion automatically.
🔒 SQL Injection Safe ⚡ Pre-compiled 🔄 Reusable 🎯 Type Safe
Parameters are escaped/sanitized SQL parsed once, executed many times — Same object with different param values setInt(), setString() enforce correct data
automatically faster each run types
Java
// PreparedStatement example
String sql = "INSERT INTO students(id, name, dept) VALUES(?, ?, ?)";
PreparedStatement pstmt = [Link](sql);
// Setting parameters (1-indexed)
[Link](1, 102);
[Link](2, "Bob");
[Link](3, "IT");
int rowsAffected = [Link]();
// Reuse with different values
[Link](1, 103);
[Link](2, "Carol");
[Link](3, "Math");
[Link]();
[Link]();
Java JDBC & Collections Framework
ResultSet Interface
ResultSet holds the data returned by a SELECT query. The cursor starts before the first row; use next() to advance. Data is accessed via getXxx(columnName/index) methods.
ResultSet Navigation Common getter methods
[Before First] ← cursor starts here • getString(col)
• getInt(col)
Row 1: Alice | CS
• getDouble(col)
Row 2: Bob | IT
• getBoolean(col)
Row 3: Carol | Math
• getDate(col)
[After Last] • getObject(col)
▲ next() moves cursor down ▲
Java
ResultSet rs = [Link]("SELECT * FROM students");
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
String dept = [Link]("dept");
[Link](id + " | " + name + " | " + dept);
}
[Link]();
Java JDBC & Collections Framework
CRUD Operations Using JDBC
CREATE (INSERT) · READ (SELECT) · UPDATE · DELETE
C CREATE R READ
pstmt = [Link]( ResultSet rs = [Link](
"INSERT INTO emp(id,name,sal) VALUES(?,?,?)"); "SELECT * FROM emp");
[Link](1,1); [Link](2,"Alice"); while([Link]()){
[Link](3,50000); [Link]([Link]("id")+
[Link](); " "+[Link]("name"));
}
U UPDATE D DELETE
pstmt = [Link]( pstmt = [Link](
"UPDATE emp SET sal=? WHERE id=?"); "DELETE FROM emp WHERE id=?");
[Link](1, 60000); [Link](1, 1);
[Link](2, 1); int n = [Link]();
int n = [Link](); [Link](n+" row deleted");
Java JDBC & Collections Framework
Complete JDBC Program — End to End
Java
import [Link].*;
public class JdbcExample {
public static void main(String[] args) throws Exception {
// Step 1: Load driver (optional in JDBC 4.0+)
[Link]("[Link]");
// Step 2: Establish connection
String url = "jdbc:mysql://localhost:3306/college";
Connection con = [Link](url, "root", "pass");
// Step 3: Create PreparedStatement
String sql = "INSERT INTO students(id, name, dept) VALUES(?,?,?)";
PreparedStatement ps = [Link](sql);
[Link](1, 101); [Link](2, "Alice"); [Link](3, "CSE");
[Link]();
// Step 4: Execute SELECT query
Statement st = [Link]();
ResultSet rs = [Link]("SELECT * FROM students");
while ([Link]()) {
[Link]("%-5d %-15s %-10s%n",
[Link]("id"), [Link]("name"), [Link]("dept"));
}
// Step 5: Close resources
[Link](); [Link](); [Link](); [Link]();
[Link]("Done!");
}
}
Java JDBC & Collections Framework
Part 2: Collection
Framework in Java
Collection Framework Hierarchy
<<interface>>
Iterable<E>
<<interface>>
Collection<E>
<<interface>> <<interface>> <<interface>>
List<E> Set<E> Queue<E>
ArrayList LinkedList HashSet TreeSet PriorityQueue ArrayDeque
<<interface>>
Map<K,V>
HashMap LinkedHashMap TreeMap Hashtable
Note: Map does not extend Collection
Java JDBC & Collections Framework
ArrayList
ArrayList is a resizable array implementation of the List interface. It maintains insertion order, allows duplicates and null values, and provides O(1) random access by index.
Internal Array Representation:
O(1) get/set by index O(n) insert at middle
Alice Bob Carol Dave
[0] [3] size=4 / capacity=7
O(1)* add at end (amortized) O(n) remove from middle
Java
import [Link];
ArrayList<String> list = new ArrayList<>();
// Add elements
[Link]("Alice"); [Link]("Bob"); [Link]("Carol");
[Link](1, "Dave"); // insert at index 1
// Access
[Link]([Link](0)); // Alice
[Link]([Link]()); // 4
// Iterate
for (String s : list) [Link](s);
// Remove
[Link]("Bob"); // by value
[Link](0); // by index
// Other methods
[Link]("Carol"); // true
[Link]("Carol"); // returns index
[Link](); // remove all
Java JDBC & Collections Framework
LinkedList
LinkedList implements both List and Deque. Uses a doubly-linked node structure — each node holds data plus references to previous and next nodes. Efficient insertion/
deletion but slower random access.
Doubly Linked List Structure:
⟺ ⟺ ⟺
Alice Bob Carol
null
prev | next prev | next prev | next ⟺ null
ArrayList LinkedList
• Fast access O(1) • Slow access O(n)
• Slow insert/delete at middle O(n) • Fast insert/delete O(1) at known pos
• Less memory • More memory (node overhead)
Java
LinkedList<String> ll = new LinkedList<>();
[Link]("Alice"); [Link]("Zara"); [Link]("Bob");
[Link]([Link]()); // Zara
[Link]([Link]()); // Bob
[Link](); [Link]();
// Use as Stack: push/pop | Use as Queue: offer/poll
Java JDBC & Collections Framework
Stack ([Link])
Stack extends Vector and represents a Last-In, First-Out (LIFO) data structure. The top of the stack is where elements are added (pushed) and removed (popped).
LIFO — Stack Visualization
← TOP
push(40) →
30 (top) ← pop()
Java
20 import [Link];
Stack<Integer> stack = new Stack<>();
// push - add to top
10 [Link](10);
[Link](20);
[Link](30);
5 (bottom) // peek - view top without removing
[Link]([Link]()); // 30
─── BASE ─── // pop - remove from top
[Link]([Link]()); // 30
[Link]([Link]()); // 20
// isEmpty
[Link]([Link]()); // false
[Link]([Link]()); // 1
Java JDBC & Collections Framework [Link]([Link](10));// 1 (position from top)
Queue & PriorityQueue
Queue is a First-In, First-Out (FIFO) structure. PriorityQueue orders elements by natural ordering or a custom Comparator — the head is always the smallest (or highest priority)
element.
FIFO Queue PriorityQueue (Min-Heap)
REAR → offer() poll() → FRONT HEAD (smallest) → peek() always returns minimum element
30 20 10 5 5 10 20 30
⟵ elements removed from here peek() / poll() returns 5 (minimum)
Java
import [Link];
PriorityQueue<Integer> pq = new PriorityQueue<>();
[Link](30); [Link](10); [Link](20); [Link](5);
[Link]([Link]()); // 5 (min-element, doesn't remove)
[Link]([Link]()); // 5 (removes min)
[Link]([Link]()); // 10
// Custom order (Max-Heap):
PriorityQueue<Integer> maxPQ =
new PriorityQueue<>((a,b) -> b - a);
[Link](5); [Link](30); [Link](10);
[Link]([Link]()); // 30 (max first)
Java JDBC & Collections Framework
Map Interface & HashMap
Map stores key-value pairs. Keys are unique; values can repeat. HashMap uses a hash table internally — average O(1) for get/put. Does NOT maintain insertion order. Allows
one null key and multiple null values.
Java
HashMap Internal Buckets
import [Link];
0 null
HashMap<String, Integer> map = new HashMap<>();
// put key-value pairs
1 name → Alice [Link]("Alice", 95);
[Link]("Bob", 82);
[Link]("Carol", 90);
2 age → 25
// get value by key
3 null [Link]([Link]("Alice")); // 95
// check key / value existence
4 city → Delhi → score → 90 [Link]("Bob"); // true
[Link](100); // false
5 dept → CS
// iterate
for ([Link]<String, Integer> e : [Link]()) {
[Link]([Link]() + " = " + [Link]());
}
// remove
[Link]("Bob");
[Link]([Link]()); // 2
Java JDBC & Collections Framework
Map Implementations Comparison
Class Ordering Null Keys Thread-Safe Performance Notes
HashMap No ordering 1 null key ❌ Not thread-safe O(1) avg Best general-purpose Map
LinkedHashMap Insertion order 1 null key ❌ Not thread-safe O(1) avg Maintains insertion order
TreeMap Sorted by key No null keys ❌ Not thread-safe O(log n) Implements NavigableMap
Hashtable No ordering No null keys ✅ Synchronized O(1) avg Legacy class, use ConcurrentHashMap
Java
// LinkedHashMap - preserves insertion order
LinkedHashMap<String, Integer> lhm = new LinkedHashMap<>();
[Link]("C", 3); [Link]("A", 1); [Link]("B", 2);
// Prints: C=3, A=1, B=2 (insertion order)
// TreeMap - sorted by key
TreeMap<String, Integer> tm = new TreeMap<>();
[Link]("C", 3); [Link]("A", 1); [Link]("B", 2);
// Prints: A=1, B=2, C=3 (sorted alphabetical)
[Link]([Link]()); // A
[Link]([Link]()); // C
Java JDBC & Collections Framework
Set Interface — HashSet, LinkedHashSet, TreeSet
Set stores unique elements only — no duplicates. Adding a duplicate silently ignores it. Three main implementations differ in ordering and performance.
HashSet HashSet<String> hs = new HashSet<>();
[Link]("Alice"); [Link]("Bob"); [Link]("Alice");
[Link]([Link]()); // 2 (no duplicate)
Order: No ordering
[Link]("Bob"); // true
Null: Allows 1 null
Perf: O(1)
LinkedHashSet LinkedHashSet<String> lhs = new LinkedHashSet<>();
[Link]("C"); [Link]("A"); [Link]("B");
// Iteration preserves insertion order: C, A, B
Order: Insertion order
Null: Allows 1 null
Perf: O(1)
TreeSet TreeSet<Integer> ts = new TreeSet<>();
[Link](30); [Link](10); [Link](20);
[Link]([Link]()); // 10
Order: Sorted (natural)
[Link]([Link]()); // 30
Null: No null allowed
Perf: O(log n)
Java JDBC & Collections Framework
Collections Utility Class & Iterators
[Link] — Utility Methods Iterator & For-Each
Java
sort(list) Natural sort of list elements
// 3 ways to iterate
List<String> list = new ArrayList<>();
sort(list, comparator) Custom sort using Comparator [Link]("A"); [Link]("B");
reverse(list) Reverses the list order // 1. For-each loop
for (String s : list)
[Link](s);
shuffle(list) Randomly shuffles elements
// 2. Iterator
Iterator<String> it = [Link]();
min(collection) Returns the minimum element while ([Link]())
[Link]([Link]());
max(collection) Returns the maximum element
// 3. forEach (Java 8+)
[Link]([Link]::println);
frequency(coll, obj) Count of obj in collection
unmodifiableList(list) Returns read-only view
synchronizedList(list) Returns thread-safe list
Java
// Sorting example
List<Integer> nums = new ArrayList<>(
[Link](3,1,4,1,5,9,2,6));
[Link](nums);
[Link](nums); // [1,1,2,3,4,5,6,9]
[Link](nums);
[Link]([Link](nums)); // 9
Java JDBC & Collections Framework
Collection Classes — Quick Comparison
Class Interface Order Duplicates Null Thread-Safe Performance
ArrayList List Insertion ✅ ✅ ❌ O(1) get
LinkedList List/Deque Insertion ✅ ✅ ❌ O(1) add/remove
Stack List LIFO ✅ ✅ ✅ O(1) push/pop
PriorityQueue Queue Priority ✅ ❌ ❌ O(log n)
HashSet Set None ❌ 1 null ❌ O(1)
LinkedHashSet Set Insertion ❌ 1 null ❌ O(1)
TreeSet Set Sorted ❌ ❌ ❌ O(log n)
HashMap Map None keys: ❌ 1 null key ❌ O(1)
LinkedHashMap Map Insertion keys: ❌ 1 null key ❌ O(1)
TreeMap Map Sorted keys: ❌ ❌ ❌ O(log n)
Java JDBC & Collections Framework
Key Takeaways
JDBC Architecture ArrayList vs LinkedList
Java App → JDBC API → DriverManager → Driver → Database ArrayList for random access; LinkedList for frequent insertions
Type 4 Driver Stack & Queue
Pure Java thin driver is the most widely used JDBC driver type Stack = LIFO (push/pop); PriorityQueue = priority ordering (poll)
PreparedStatement HashMap
Always prefer over Statement to prevent SQL injection Key-value store, O(1) avg, no ordering, 1 null key allowed
CRUD with JDBC Set uniqueness
executeQuery() for SELECT, executeUpdate() for DML operations Sets guarantee unique elements; TreeSet keeps them sorted
Java JDBC & Collections Framework · Complete Reference Guide