Programming in Java
Unit 14: JDBC Database Programming
From raw SQL to enterprise CRUD apps โ master JDBC architecture, driver types, PreparedStatement, transactions, and build real database applications in Java.
โฑ๏ธ Time to Complete: 7 hrs theory + 6 hrs lab | ๐ฐ Earning Potential: โน10Kโโน40K/month | ๐ 30 MCQs (Bloom's Mapped)
๐ผ Jobs this unlocks: Java Backend Developer (โน5โ10 LPA) | Full-Stack Developer (โน6โ14 LPA) | Database Application Developer (โน4โ8 LPA)
Opening Hook โ The Database Behind Every Ticket
๐ How IRCTC Handles 12 Lakh Simultaneous Database Queries During Tatkal
Every morning at 10:00 AM, millions of Indians slam the IRCTC booking page. In a 60-second Tatkal window, the system handles 12 lakh (1.2 million) simultaneous database queries. Each search, each seat check, each booking confirmation is a JDBC PreparedStatement flying through a managed connection pool to an Oracle/PostgreSQL database backend.
Behind the scenes, IRCTC's Java application servers maintain pools of pre-opened database connections (using HikariCP/C3P0). When you click "Book Now," your request grabs a connection from the pool, executes a parameterised SQL query (SELECT available_seats FROM trains WHERE train_no=? AND date=?), reads the ResultSet, and if seats exist, fires an INSERT INTO bookings โ all within 200 milliseconds.
Every ticket you book = one JDBC call. Every "Seat not available" pop-up = another JDBC call. Every payment confirmation = yet another JDBC call. Without JDBC, there is no IRCTC, no online banking, no e-commerce checkout, no digital India.
Learning Outcomes โ Bloom's Taxonomy Mapped
| Bloom's Level | Learning Outcome |
|---|---|
| ๐ต Remember | List the four components of JDBC API (Driver, Connection, Statement, ResultSet) and name the four JDBC driver types |
| ๐ต Remember | Recall the syntax for DriverManager.getConnection() and the steps to execute a SQL query in Java |
| ๐ข Understand | Explain the difference between Statement, PreparedStatement, and CallableStatement with real-world examples |
| ๐ข Understand | Describe how SQL injection attacks work and why PreparedStatement prevents them |
| ๐ก Apply | Write complete Java CRUD programs (INSERT, SELECT, UPDATE, DELETE) using PreparedStatement with MySQL |
| ๐ก Apply | Implement transaction management using setAutoCommit(false), commit(), and rollback() |
| ๐ Analyze | Compare the four JDBC driver types and determine which is suitable for different deployment scenarios |
| ๐ Analyze | Analyze connection pooling benefits and diagnose connection leak problems in a Java application |
| ๐ด Evaluate | Evaluate whether a given code snippet is vulnerable to SQL injection and propose fixes |
| ๐ด Evaluate | Assess the trade-offs between batch processing vs individual inserts for bulk data operations |
| ๐ฃ Create | Design and build a complete College Library CRUD application with MySQL backend |
| ๐ฃ Create | Architect a Student Marks Entry System with transaction-safe multi-table updates |
Concept Explanation โ JDBC from Scratch
1. JDBC Architecture โ The 4-Tier Bridge
Think of JDBC as a universal translator between your Java program and any database. Just like a NEFT wire transfer โ your Java app (your bank) sends SQL (payment instruction) through JDBC (banking network) to the Database (recipient bank). You don't need to know the internal workings of the recipient bank; JDBC handles the protocol.
๐๏ธ JDBC 4-Tier Architecture
Tier 1 โ Java Application: Your Java code that creates SQL queries, processes results, and handles business logic. This is what YOU write.
Tier 2 โ JDBC API: The java.sql and javax.sql packages. Provides interfaces like Connection, Statement, ResultSet, PreparedStatement. This is the "contract" โ it defines WHAT can be done.
Tier 3 โ JDBC Driver Manager & Driver: The DriverManager class loads the appropriate driver. The driver itself (e.g., MySQL Connector/J, Oracle JDBC) implements the JDBC interfaces. This is the "translator" โ it knows HOW to talk to a specific database.
Tier 4 โ Database: The actual database server (MySQL, PostgreSQL, Oracle, SQL Server). Stores data, executes SQL, returns results.
Architecture Diagram
โโโโโโโโโโโโโโโโโโโโโโโโ
โ JAVA APPLICATION โ โ Your code (main(), servlets, Spring)
โ (Tier 1) โ
โโโโโโโโโโฌโโโโโโโโโโโโโโ
โ calls java.sql API
โโโโโโโโโโผโโโโโโโโโโโโโโ
โ JDBC API โ โ Interfaces: Connection, Statement,
โ (Tier 2) โ ResultSet, PreparedStatement
โโโโโโโโโโฌโโโโโโโโโโโโโโ
โ delegates to driver
โโโโโโโโโโผโโโโโโโโโโโโโโ
โ JDBC DRIVER โ โ mysql-connector-j.jar / ojdbc.jar
โ (Tier 3) โ Translates JDBC calls โ DB protocol
โโโโโโโโโโฌโโโโโโโโโโโโโโ
โ network (TCP/IP)
โโโโโโโโโโผโโโโโโโโโโโโโโ
โ DATABASE โ โ MySQL, PostgreSQL, Oracle, SQL Server
โ (Tier 4) โ Executes SQL, returns rows
โโโโโโโโโโโโโโโโโโโโโโโโ
SELECT query runs against the Oracle DB โ and the result appears on your screen in under 500ms.
2. JDBC API Overview โ The Core Interfaces
The JDBC API lives in two packages: java.sql (core) and javax.sql (extensions like connection pooling, RowSets). Here are the key players:
| Interface / Class | What It Does | Analogy |
|---|---|---|
DriverManager | Factory that creates Connection objects. Loads the right driver for your DB URL. | Like a telephone exchange โ you dial a number (URL), it connects you to the right person (database) |
Connection | Represents an active session with the database. Used to create statements and manage transactions. | Like an open phone line โ you can talk (send SQL) as long as the connection is alive |
Statement | Sends static SQL strings to the database. Simple but vulnerable to SQL injection. | Like a postcard โ anyone can read and modify the message |
PreparedStatement | Pre-compiled SQL with ? placeholders. Faster, safer, reusable. | Like a sealed registered letter โ the message template is fixed, only the data changes |
CallableStatement | Calls stored procedures in the database. | Like calling a specialist โ you don't tell them how to operate, just what you need done |
ResultSet | Holds rows returned by a SELECT query. Navigate with next(), read with getInt(), getString(). | Like a stack of answer sheets โ you flip through one by one, reading each student's marks |
The 5-Step JDBC Workflow
Java // Step 1: Load the driver (auto-loaded in JDBC 4.0+) // Class.forName("com.mysql.cj.jdbc.Driver"); // Only needed for older JDBC // Step 2: Establish connection Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/college_db", "root", "password"); // Step 3: Create statement PreparedStatement pstmt = conn.prepareStatement( "SELECT * FROM students WHERE roll_no = ?"); pstmt.setInt(1, 101); // Step 4: Execute query & process ResultSet ResultSet rs = pstmt.executeQuery(); while (rs.next()) { System.out.println(rs.getString("name") + " โ " + rs.getInt("marks")); } // Step 5: Close resources (reverse order) rs.close(); pstmt.close(); conn.close();
3. JDBC Driver Types โ Type 1 to Type 4
A JDBC driver is the "translator" that converts JDBC calls into the specific protocol your database understands. There are four types, each with different trade-offs:
| Type | Name | How It Works | Pros | Cons | Used Today? |
|---|---|---|---|---|---|
| Type 1 | JDBC-ODBC Bridge | JDBC โ ODBC โ Database. Uses Windows ODBC drivers as middleware. | Easy setup for MS Access | Slow, platform-dependent, removed in Java 8+ | โ Obsolete |
| Type 2 | Native-API Driver | JDBC โ Native C/C++ library โ Database. Requires DB vendor's native client installed. | Faster than Type 1 | Platform-dependent, requires native installation | โ ๏ธ Rare (Oracle OCI) |
| Type 3 | Network Protocol Driver | JDBC โ Middleware server โ Database. 3-tier architecture via a middleware application server. | No client-side DB library needed | Requires middleware server, extra network hop | โ ๏ธ Niche (app servers) |
| Type 4 | Thin Driver (Pure Java) | JDBC โ Database directly via TCP/IP. 100% Java, no native code. | Fastest, platform-independent, no extra installation | DB-specific (one driver per DB) | โ Industry standard |
4. Statement vs PreparedStatement vs CallableStatement
| Feature | Statement | PreparedStatement | CallableStatement |
|---|---|---|---|
| SQL Type | Static SQL strings | Parameterised SQL with ? | Stored procedure calls |
| Compilation | Compiled every execution | Pre-compiled once, executed many times | Pre-compiled stored procedure |
| Performance | Slowest (re-parsed each time) | Fast (cached execution plan) | Fastest (DB-side optimised) |
| SQL Injection | โ Vulnerable | โ Safe (parameterised) | โ Safe |
| Use Case | Quick testing, DDL (CREATE TABLE) | All CRUD operations | Complex business logic in DB |
| Example | stmt.execute("DROP TABLE...") | pstmt.setString(1, name) | cstmt.registerOutParameter(...) |
โ ๏ธ SQL Injection โ Why Statement is Dangerous
Java โ VULNERABLE CODE // โ DANGEROUS: String concatenation with user input String userInput = "'; DROP TABLE students; --"; String sql = "SELECT * FROM students WHERE name = '" + userInput + "'"; stmt.execute(sql); // Executed SQL: SELECT * FROM students WHERE name = ''; DROP TABLE students; --' // ๐ YOUR ENTIRE STUDENTS TABLE IS DELETED!
Java โ SAFE CODE // โ SAFE: PreparedStatement treats input as DATA, not SQL code String userInput = "'; DROP TABLE students; --"; PreparedStatement pstmt = conn.prepareStatement( "SELECT * FROM students WHERE name = ?"); pstmt.setString(1, userInput); ResultSet rs = pstmt.executeQuery(); // The input is treated as a literal string โ no SQL execution. // โ Table is SAFE. Query returns 0 rows (no student with that silly name).
Statement with string concatenation instead of PreparedStatement. The attacker extracted 50,000 customer records including PAN numbers. CERT-In now mandates parameterised queries for all government and BFSI applications.
5. ResultSet Navigation
A ResultSet is like a cursor pointing to rows returned by a SELECT query. You start before the first row and call next() to advance:
| Method | What It Does | Return Type |
|---|---|---|
next() | Moves cursor to next row. Returns false when no more rows. | boolean |
getInt("column") | Gets integer value from named column | int |
getString("column") | Gets string value from named column | String |
getDouble("column") | Gets double value from named column | double |
getDate("column") | Gets date value from named column | java.sql.Date |
getInt(1) | Gets value by column index (1-based) | int |
wasNull() | Checks if the last value read was SQL NULL | boolean |
Java ResultSet rs = pstmt.executeQuery(); // Pattern: while loop with next() while (rs.next()) { int rollNo = rs.getInt("roll_no"); String name = rs.getString("name"); double marks = rs.getDouble("marks"); Date dob = rs.getDate("dob"); System.out.printf("%-5d %-20s %.1f %s%n", rollNo, name, marks, dob); } rs.close();
rs.getInt(1) returns the FIRST column. rs.getInt(0) throws SQLException. This trips up every Java student who is used to 0-based arrays.
6. CRUD Operations โ Full Code for Each
Setup: Create the Database & Table
SQL โ Run in MySQL CREATE DATABASE college_db; USE college_db; CREATE TABLE books ( book_id INT PRIMARY KEY AUTO_INCREMENT, title VARCHAR(100) NOT NULL, author VARCHAR(80), isbn VARCHAR(20) UNIQUE, price DECIMAL(8,2), copies INT DEFAULT 1, added_date DATE DEFAULT (CURRENT_DATE) );
CREATE โ INSERT a new book
Java import java.sql.*; public class InsertBook { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/college_db"; String user = "root"; String pass = "password"; String sql = "INSERT INTO books (title, author, isbn, price, copies) VALUES (?, ?, ?, ?, ?)"; try (Connection conn = DriverManager.getConnection(url, user, pass); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setString(1, "Data Structures Using Java"); pstmt.setString(2, "R. Lafore"); pstmt.setString(3, "978-0-13-257627-7"); pstmt.setDouble(4, 599.00); pstmt.setInt(5, 5); int rows = pstmt.executeUpdate(); System.out.println(rows + " book(s) inserted successfully!"); } catch (SQLException e) { e.printStackTrace(); } } }
READ โ SELECT all books
Java public class SelectBooks { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/college_db"; String sql = "SELECT * FROM books ORDER BY title"; try (Connection conn = DriverManager.getConnection(url, "root", "password"); PreparedStatement pstmt = conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery()) { System.out.printf("%-5s %-30s %-20s %-10s %-6s%n", "ID", "Title", "Author", "Price(โน)", "Copies"); System.out.println("โ".repeat(75)); while (rs.next()) { System.out.printf("%-5d %-30s %-20s โน%-9.2f %-6d%n", rs.getInt("book_id"), rs.getString("title"), rs.getString("author"), rs.getDouble("price"), rs.getInt("copies")); } } catch (SQLException e) { e.printStackTrace(); } } }
UPDATE โ Modify book price
Java public class UpdateBook { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/college_db"; String sql = "UPDATE books SET price = ?, copies = ? WHERE book_id = ?"; try (Connection conn = DriverManager.getConnection(url, "root", "password"); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setDouble(1, 649.00); // new price pstmt.setInt(2, 10); // new copies pstmt.setInt(3, 1); // book_id int rows = pstmt.executeUpdate(); System.out.println(rows + " book(s) updated."); } catch (SQLException e) { e.printStackTrace(); } } }
DELETE โ Remove a book
Java public class DeleteBook { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/college_db"; String sql = "DELETE FROM books WHERE book_id = ?"; try (Connection conn = DriverManager.getConnection(url, "root", "password"); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setInt(1, 1); // book_id to delete int rows = pstmt.executeUpdate(); if (rows > 0) System.out.println("Book deleted successfully."); else System.out.println("No book found with that ID."); } catch (SQLException e) { e.printStackTrace(); } } }
7. Transaction Management
A transaction is a group of SQL operations that must ALL succeed or ALL fail. Think of it like a bank transfer: debit from Account A AND credit to Account B must both happen โ or neither should.
๐ ACID Properties
A โ Atomicity: All operations succeed or all are rolled back. No partial execution.
C โ Consistency: Database moves from one valid state to another. No rule violations.
I โ Isolation: Concurrent transactions don't interfere with each other.
D โ Durability: Once committed, data survives crashes.
Java โ Transaction Example: Library Book Issue public class IssueBookTransaction { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/college_db"; Connection conn = null; try { conn = DriverManager.getConnection(url, "root", "password"); // โ Disable auto-commit โ start transaction conn.setAutoCommit(false); // โก Decrease copies in books table PreparedStatement ps1 = conn.prepareStatement( "UPDATE books SET copies = copies - 1 WHERE book_id = ? AND copies > 0"); ps1.setInt(1, 101); int updated = ps1.executeUpdate(); if (updated == 0) { throw new SQLException("No copies available!"); } // โข Insert issue record PreparedStatement ps2 = conn.prepareStatement( "INSERT INTO book_issues (book_id, student_id, issue_date) VALUES (?, ?, CURDATE())"); ps2.setInt(1, 101); ps2.setInt(2, 2023001); ps2.executeUpdate(); // โฃ COMMIT โ both operations succeed conn.commit(); System.out.println("โ Book issued successfully!"); } catch (SQLException e) { try { if (conn != null) { // โค ROLLBACK โ undo everything if any step fails conn.rollback(); System.out.println("โ Transaction rolled back: " + e.getMessage()); } } catch (SQLException ex) { ex.printStackTrace(); } } finally { try { if (conn != null) { conn.setAutoCommit(true); conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }
8. Batch Processing
When you need to insert 1,000 records, executing 1,000 individual queries is painfully slow (1,000 network round trips). Batch processing bundles them into a single trip:
Java โ Batch INSERT String sql = "INSERT INTO students (name, roll_no, branch) VALUES (?, ?, ?)"; PreparedStatement pstmt = conn.prepareStatement(sql); String[][] data = { {"Amit Sharma", "101", "CSE"}, {"Priya Verma", "102", "IT"}, {"Rahul Singh", "103", "ECE"}, {"Sneha Patel", "104", "CSE"}, {"Vikram Reddy", "105", "ME"} }; for (String[] row : data) { pstmt.setString(1, row[0]); pstmt.setInt(2, Integer.parseInt(row[1])); pstmt.setString(3, row[2]); pstmt.addBatch(); // add to batch, don't execute yet } int[] results = pstmt.executeBatch(); // execute ALL at once! System.out.println("Inserted " + results.length + " records in one batch.");
9. Connection Pooling
Problem: Creating a new database connection takes 200โ500ms (TCP handshake + authentication). If your app gets 100 requests/second, creating 100 new connections per second is a disaster.
Solution: Connection Pooling. Keep a "pool" of pre-created connections. When a request needs a connection, borrow one from the pool. When done, return it (don't close it). Think of it like an auto-rickshaw stand โ rickshaws wait in a line, passengers take the next available one, and the rickshaw returns to the stand after the trip.
| Feature | Without Pool | With Pool (HikariCP) |
|---|---|---|
| Connection time per request | 200โ500ms | ~1ms (pre-created) |
| Max concurrent connections | Unlimited (DB crashes) | Configurable (e.g., 10โ50) |
| Resource management | Manual close (leak risk) | Auto-reclaim idle connections |
| Production readiness | โ | โ |
Java โ HikariCP Connection Pool (Conceptual) // In pom.xml: add com.zaxxer:HikariCP:5.1.0 dependency HikariConfig config = new HikariConfig(); config.setJdbcUrl("jdbc:mysql://localhost:3306/college_db"); config.setUsername("root"); config.setPassword("password"); config.setMaximumPoolSize(10); // max 10 connections in pool HikariDataSource ds = new HikariDataSource(config); // Get connection from pool (near-instant!) try (Connection conn = ds.getConnection()) { // use connection... } // auto-returned to pool on close
10. RowSet โ Disconnected Data Access
A RowSet is a wrapper around ResultSet that can work in disconnected mode. It fetches data, closes the connection, and lets you work with the data offline. Think of it like downloading a PDF vs reading online โ you can read the PDF even without internet.
| Type | Connected? | Use Case |
|---|---|---|
JdbcRowSet | โ Connected | Enhanced ResultSet wrapper |
CachedRowSet | โ Disconnected | Work with data offline, sync later |
WebRowSet | โ Disconnected | XML-based data transfer |
FilteredRowSet | โ Disconnected | Client-side filtering |
JoinRowSet | โ Disconnected | Join data from multiple RowSets |
11. Database Metadata
DatabaseMetaData lets your Java program discover information about the database โ name, version, tables, columns โ programmatically:
Java DatabaseMetaData meta = conn.getMetaData(); System.out.println("Database: " + meta.getDatabaseProductName()); System.out.println("Version: " + meta.getDatabaseProductVersion()); System.out.println("Driver: " + meta.getDriverName()); System.out.println("URL: " + meta.getURL()); // List all tables ResultSet tables = meta.getTables(null, null, "%", new String[]{"TABLE"}); while (tables.next()) { System.out.println("Table: " + tables.getString("TABLE_NAME")); }
12. Full Application โ College Library CRUD App
Java โ LibraryCRUD.java import java.sql.*; import java.util.Scanner; public class LibraryCRUD { private static final String URL = "jdbc:mysql://localhost:3306/college_db"; private static final String USER = "root"; private static final String PASS = "password"; public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (true) { System.out.println("\n๐ COLLEGE LIBRARY SYSTEM"); System.out.println("1. Add Book"); System.out.println("2. Search Books"); System.out.println("3. Update Book"); System.out.println("4. Delete Book"); System.out.println("5. View All Books"); System.out.println("0. Exit"); System.out.print("Choose: "); int choice = sc.nextInt(); sc.nextLine(); switch (choice) { case 1: addBook(sc); break; case 2: searchBooks(sc); break; case 3: updateBook(sc); break; case 4: deleteBook(sc); break; case 5: viewAllBooks(); break; case 0: System.out.println("Goodbye!"); return; default: System.out.println("Invalid choice."); } } } static void addBook(Scanner sc) { System.out.print("Title: "); String title = sc.nextLine(); System.out.print("Author: "); String author = sc.nextLine(); System.out.print("ISBN: "); String isbn = sc.nextLine(); System.out.print("Price: "); double price = sc.nextDouble(); System.out.print("Copies: "); int copies = sc.nextInt(); String sql = "INSERT INTO books (title, author, isbn, price, copies) VALUES (?,?,?,?,?)"; try (Connection c = DriverManager.getConnection(URL,USER,PASS); PreparedStatement p = c.prepareStatement(sql)) { p.setString(1,title); p.setString(2,author); p.setString(3,isbn); p.setDouble(4,price); p.setInt(5,copies); System.out.println("โ " + p.executeUpdate() + " book added."); } catch (SQLException e) { System.out.println("Error: "+e.getMessage()); } } static void searchBooks(Scanner sc) { System.out.print("Search keyword: "); String kw = "%" + sc.nextLine() + "%"; String sql = "SELECT * FROM books WHERE title LIKE ? OR author LIKE ?"; try (Connection c = DriverManager.getConnection(URL,USER,PASS); PreparedStatement p = c.prepareStatement(sql)) { p.setString(1,kw); p.setString(2,kw); ResultSet rs = p.executeQuery(); while (rs.next()) { System.out.printf("[%d] %s by %s โ โน%.2f (%d copies)%n", rs.getInt("book_id"), rs.getString("title"), rs.getString("author"), rs.getDouble("price"), rs.getInt("copies")); } } catch (SQLException e) { e.printStackTrace(); } } static void updateBook(Scanner sc) { System.out.print("Book ID to update: "); int id = sc.nextInt(); sc.nextLine(); System.out.print("New price: "); double price = sc.nextDouble(); System.out.print("New copies: "); int copies = sc.nextInt(); String sql = "UPDATE books SET price=?, copies=? WHERE book_id=?"; try (Connection c = DriverManager.getConnection(URL,USER,PASS); PreparedStatement p = c.prepareStatement(sql)) { p.setDouble(1,price); p.setInt(2,copies); p.setInt(3,id); System.out.println("โ " + p.executeUpdate() + " book updated."); } catch (SQLException e) { e.printStackTrace(); } } static void deleteBook(Scanner sc) { System.out.print("Book ID to delete: "); int id = sc.nextInt(); String sql = "DELETE FROM books WHERE book_id=?"; try (Connection c = DriverManager.getConnection(URL,USER,PASS); PreparedStatement p = c.prepareStatement(sql)) { p.setInt(1,id); System.out.println("๐๏ธ " + p.executeUpdate() + " book deleted."); } catch (SQLException e) { e.printStackTrace(); } } static void viewAllBooks() { String sql = "SELECT * FROM books ORDER BY title"; try (Connection c = DriverManager.getConnection(URL,USER,PASS); PreparedStatement p = c.prepareStatement(sql); ResultSet rs = p.executeQuery()) { System.out.printf("%-5s %-30s %-20s %-10s %-6s%n", "ID","Title","Author","Price","Copies"); while (rs.next()) { System.out.printf("%-5d %-30s %-20s โน%-9.2f %-6d%n", rs.getInt(1),rs.getString(2),rs.getString(3), rs.getDouble(5),rs.getInt(6)); } } catch (SQLException e) { e.printStackTrace(); } } }
13. Full Application โ Student Marks Entry System
SQL โ Setup CREATE TABLE students ( student_id INT PRIMARY KEY, name VARCHAR(60) NOT NULL, branch VARCHAR(10), semester INT ); CREATE TABLE marks ( mark_id INT PRIMARY KEY AUTO_INCREMENT, student_id INT, subject VARCHAR(40), marks_obt INT, max_marks INT DEFAULT 100, FOREIGN KEY (student_id) REFERENCES students(student_id) );
Java โ StudentMarksSystem.java import java.sql.*; import java.util.Scanner; public class StudentMarksSystem { static final String URL = "jdbc:mysql://localhost:3306/college_db"; public static void main(String[] args) throws SQLException { Scanner sc = new Scanner(System.in); System.out.print("Enter Student ID: "); int sid = sc.nextInt(); sc.nextLine(); System.out.print("Enter Name: "); String name = sc.nextLine(); System.out.print("Branch: "); String branch = sc.nextLine(); System.out.print("Semester: "); int sem = sc.nextInt(); sc.nextLine(); Connection conn = DriverManager.getConnection(URL, "root", "password"); conn.setAutoCommit(false); // transaction start try { // Insert student PreparedStatement ps1 = conn.prepareStatement( "INSERT INTO students (student_id, name, branch, semester) VALUES (?,?,?,?)"); ps1.setInt(1,sid); ps1.setString(2,name); ps1.setString(3,branch); ps1.setInt(4,sem); ps1.executeUpdate(); // Insert marks for 5 subjects String[] subjects = {"Java", "DBMS", "OS", "Maths", "English"}; PreparedStatement ps2 = conn.prepareStatement( "INSERT INTO marks (student_id, subject, marks_obt) VALUES (?,?,?)"); for (String sub : subjects) { System.out.print("Marks in " + sub + ": "); int m = sc.nextInt(); ps2.setInt(1, sid); ps2.setString(2, sub); ps2.setInt(3, m); ps2.addBatch(); } ps2.executeBatch(); conn.commit(); // all or nothing System.out.println("โ Student & marks saved successfully!"); } catch (SQLException e) { conn.rollback(); System.out.println("โ Rolled back: " + e.getMessage()); } finally { conn.setAutoCommit(true); conn.close(); } } }
Learn by Doing โ 3-Tier Lab: College Library CRUD with MySQL
๐ข Tier 1 โ GUIDED: Setup MySQL + First JDBC Connection
Step 1: Install MySQL Server
Download MySQL Community Server from dev.mysql.com/downloads. During setup, set root password to password (for learning only). Verify installation:
Terminal mysql -u root -p # Enter password when prompted SHOW DATABASES;
Step 2: Create Database & Table
SQL CREATE DATABASE college_db; USE college_db; CREATE TABLE books ( book_id INT PRIMARY KEY AUTO_INCREMENT, title VARCHAR(100) NOT NULL, author VARCHAR(80), isbn VARCHAR(20) UNIQUE, price DECIMAL(8,2), copies INT DEFAULT 1 ); INSERT INTO books (title,author,isbn,price,copies) VALUES ('Let Us C','Yashavant Kanetkar','978-81-8333-163-0',350.00,8);
Step 3: Download MySQL Connector/J
Download mysql-connector-j-8.x.x.jar from dev.mysql.com/downloads/connector/j/. Place it in your project's lib/ folder.
Step 4: Write Your First JDBC Program
Create TestConnection.java:
Java import java.sql.*; public class TestConnection { public static void main(String[] args) { try (Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/college_db", "root", "password")) { System.out.println("โ Connected to MySQL!"); System.out.println("Database: " + conn.getCatalog()); } catch (SQLException e) { System.out.println("โ Connection failed: " + e.getMessage()); } } }
Step 5: Compile & Run
Terminal
javac TestConnection.java
java -cp ".;lib/mysql-connector-j-8.0.33.jar" TestConnection
๐ Congratulations! You've established your first JDBC connection. This is the foundation for everything else in this unit.
๐ก Tier 2 โ SEMI-GUIDED: Build the Complete Library CRUD
Your Mission:
Build the full LibraryCRUD.java application from Section C (concept 12) with these additions:
- Add validation: Don't allow negative prices or zero copies
- Add a "Book Count" menu option using
SELECT COUNT(*) FROM books - Use try-with-resources for all connections and statements
- Add search by ISBN (exact match) in addition to keyword search
Hints:
- For validation: check values BEFORE creating the PreparedStatement
- For COUNT:
rs.getInt(1)on aSELECT COUNT(*)query gives the count - For ISBN search:
WHERE isbn = ?(exact match, not LIKE)
generateReport() method that shows total books, total copies, average price, and most expensive book โ all using SQL aggregate functions (COUNT, SUM, AVG, MAX).
๐ด Tier 3 โ OPEN CHALLENGE: Student Marks System with Transactions
The Brief:
Build a complete Student Marks Entry & Report System with:
- Student Registration: Add student with ID, name, branch, semester
- Marks Entry: Enter marks for 5 subjects using batch processing
- Transaction Safety: If any marks entry fails, rollback student + all marks
- Report Card: Display marks, total, percentage, and pass/fail status
- Topper List: Show top 5 students by total marks using
ORDER BY ... LIMIT 5 - Branch-wise Average: Use
GROUP BY branchto show average marks per branch
Deliverable: A working Java program with MySQL backend. Include the SQL schema and at least 5 sample student records.
Problem Set โ Practice Questions
Syntax Questions (5)
- Write the JDBC URL format for connecting to a MySQL database named
shopDBonlocalhostport3306. - Write a Java statement to create a
PreparedStatementthat inserts a record into tableproducts(name, price). - Write the code to set the 1st parameter of a
PreparedStatementto the string "Laptop" and 2nd parameter to45000.00. - Write a
whileloop that reads all rows from aResultSetand prints thename(String) andprice(double) columns. - Write the three lines needed to start a transaction, commit it, and rollback on failure.
Programming Questions (8)
- Write a complete Java program that connects to MySQL and creates a table
employees(id INT PRIMARY KEY, name VARCHAR(50), salary DECIMAL(10,2)). - Write a JDBC program to insert 3 employee records using batch processing.
- Write a program that takes an employee name from the user (Scanner) and searches the
employeestable usingPreparedStatementwithLIKE. - Write a program that updates the salary of all employees in department "IT" by 10% using a single
UPDATEstatement. - Write a program that deletes all employees with salary less than โน15,000 and prints how many records were deleted.
- Write a program that uses
DatabaseMetaDatato print all table names in the current database. - Write a program that transfers โน5,000 from account A to account B using transaction management (debit A, credit B, commit/rollback).
- Write a program that reads data from the
studentstable and writes it to a CSV file usingResultSet+FileWriter.
Industry-Scale Questions (3)
๐ Industry Q1: IRCTC Booking Database
Design the database schema for a simplified IRCTC train booking system with tables: trains, passengers, bookings. Write JDBC code for:
- Searching available trains between two stations on a given date
- Booking a ticket (with transaction: check availability โ insert booking โ decrement seats)
- Cancelling a ticket (with transaction: delete booking โ increment seats โ process refund)
๐ Industry Q2: EDUARTHA Marks Management System
Build a university marks management system with tables: students, courses, enrollments, marks. Implement:
- Batch insert of marks for an entire class (40 students ร 5 subjects = 200 records)
- Generate a result sheet showing each student's marks, total, percentage, and grade
- Branch-wise topper report using
GROUP BYandMAX
๐ข Industry Q3: Inventory Management for Kirana Store
Design and implement a JDBC-based inventory management system for a local kirana (grocery) store. Include:
- Product CRUD with categories (dairy, grains, beverages, etc.)
- Stock alert: Query all products where
quantity < reorder_level - Daily sales recording with transaction (deduct stock + record sale)
Interview Questions (3)
- Infosys/TCS Interview: "What is the difference between
StatementandPreparedStatement? Why isPreparedStatementpreferred in production?" (Expected: mention SQL injection, performance, parameterisation) - Wipro Interview: "Explain connection pooling. Why is creating a new connection for every request bad? Name one connection pool library." (Expected: mention HikariCP, overhead, resource exhaustion)
- Capgemini Interview: "What happens if you call
conn.commit()whenautoCommitistrue? What is a dirty read?" (Expected: no-op for commit, explain isolation levels)
MCQ Assessment Bank โ 30 Questions (Bloom's Mapped)
Remember / Identify (Q1โQ6)
JDBC stands for:
- Java Data Base Connection
- Java Database Connectivity
- Java Data Binding Connector
- Java Dynamic Base Controller
Which package contains the core JDBC classes and interfaces?
- java.io
- java.sql
- javax.database
- java.jdbc
Which method is used to establish a JDBC connection?
Connection.open()DriverManager.getConnection()Database.connect()JDBC.createConnection()
The Type 4 JDBC driver is also known as:
- JDBC-ODBC Bridge
- Native-API Driver
- Network Protocol Driver
- Thin Driver (Pure Java)
Which method moves the cursor to the next row in a ResultSet?
advance()moveNext()next()forward()
Which method is used to execute a SELECT query in JDBC?
executeUpdate()executeQuery()execute()executeSelect()
Understand / Explain (Q7โQ12)
Why is PreparedStatement preferred over Statement for user-input queries?
- It is faster to type
- It prevents SQL injection by treating parameters as data, not SQL code
- It automatically creates the database table
- It does not require a Connection object
What does conn.setAutoCommit(false) do?
- Closes the connection
- Prevents any SQL from executing
- Starts manual transaction management โ changes are not saved until commit() is called
- Enables read-only mode
What is the purpose of connection pooling?
- To encrypt database connections
- To reuse pre-created database connections instead of creating new ones for every request
- To merge multiple databases into one
- To backup the database automatically
Why was the Type 1 (JDBC-ODBC Bridge) driver removed in Java 8?
- It was too fast and unnecessary
- It was platform-dependent, slow, and not suitable for production use
- It was too secure
- It conflicted with Type 4 drivers
What value does executeUpdate() return?
- A ResultSet
- A boolean
- The number of rows affected
- The auto-generated key
What happens when rs.next() returns false?
- The program crashes
- It means there are no more rows to read in the ResultSet
- It means the connection is closed
- It means the query had an error
Apply / Implement (Q13โQ18)
Which code correctly inserts a record using PreparedStatement?
pstmt.setString(0, "Amit");pstmt.setString(1, "Amit");pstmt.setString("name", "Amit");pstmt.addString(1, "Amit");
To execute INSERT INTO students VALUES (?, ?), which method should be called?
executeQuery()executeUpdate()executeInsert()execute()only
Given ResultSet rs from a query on table employees(id INT, name VARCHAR, salary DOUBLE), which correctly reads the salary?
rs.getString("salary")rs.getDouble("salary")rs.getInt("salary")rs.getFloat("salary")
What is the correct order to close JDBC resources?
- Connection โ Statement โ ResultSet
- ResultSet โ Connection โ Statement
- ResultSet โ Statement โ Connection
- Statement โ ResultSet โ Connection
Which code adds a SQL statement to a batch?
pstmt.executeBatch();pstmt.addBatch();pstmt.batchAdd();pstmt.appendBatch();
To get the number of tables in a database, which object do you use?
- ResultSet
- Statement
- DatabaseMetaData
- ConnectionInfo
Analyze / Compare (Q19โQ23)
A developer uses Statement with string concatenation to build SQL queries from user input. What is the primary risk?
- NullPointerException
- SQL injection attack
- ClassNotFoundException
- ArrayIndexOutOfBoundsException
An application creates a new Connection for every HTTP request and never closes them. What will happen over time?
- The application will run faster
- Database connections will exhaust, causing "Too many connections" error
- The database will automatically create more connections
- Nothing โ Java garbage collector handles connections
Why does batch processing improve performance for bulk inserts?
- It uses a different database engine
- It reduces network round trips by sending multiple SQL statements in one batch
- It compresses the data
- It bypasses the SQL parser
In a bank transfer transaction (debit A, credit B), if the credit to B fails, what should happen to the debit from A?
- It should remain โ partial transactions are fine
- It should be rolled back โ the entire transaction must be atomic
- It should be logged and manually fixed later
- It should be committed separately
Compare: a CachedRowSet fetches all data and disconnects. A JdbcRowSet stays connected. Which is better for a mobile app with intermittent connectivity?
- JdbcRowSet โ it maintains real-time data
- CachedRowSet โ it works offline after initial fetch
- Neither โ use Statement instead
- Both are identical in behaviour
Evaluate / Assess (Q24โQ27)
A developer writes: String sql = "DELETE FROM users WHERE id = " + userId; and passes it to stmt.execute(sql). Evaluate this code.
- It is correct and efficient
- It works but is vulnerable to SQL injection โ should use PreparedStatement
- It will throw a compilation error
- It is the recommended approach for DELETE operations
Assess: Should autoCommit be set to false for a simple single-row SELECT query?
- Yes โ always disable autoCommit
- No โ single read-only queries don't need manual transaction control
- Yes โ it improves performance
- No โ autoCommit(false) disables SELECT queries
A team uses DriverManager.getConnection() in every method of their web application (50+ methods). Evaluate this approach.
- It's the correct approach โ each method needs its own connection
- It's inefficient โ they should use connection pooling (e.g., HikariCP)
- It's fine โ Java automatically pools connections from DriverManager
- It's wrong โ only one connection should exist per application
Is it acceptable to store database credentials (username/password) directly in the Java source code?
- Yes โ it makes deployment easier
- No โ credentials should be in external config files or environment variables
- Yes โ if the code is not open-source
- No โ Java doesn't allow string literals for passwords
Create / Design (Q28โQ30)
You need to design a JDBC-based system that inserts 10,000 student records from a CSV file. Which approach is best?
- 10,000 individual
executeUpdate()calls - PreparedStatement with
addBatch()+executeBatch()inside a transaction - Use
Statementwith string concatenation for each row - Create 10,000 separate Connection objects
You're designing a library management system. Which JDBC feature ensures that when a book is issued, both "decrement copies" and "insert issue record" succeed or both fail?
- Batch processing
- Transaction management (setAutoCommit, commit, rollback)
- Connection pooling
- DatabaseMetaData
You need to build a reporting module that queries a large database but must work even when the network disconnects mid-session. Which JDBC component fits best?
- Statement
- PreparedStatement
- CachedRowSet
- CallableStatement
Short Answer Questions (8)
Q1. What is JDBC? What are the main components of the JDBC API?
Answer: 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 statements, and processing results.
Main components:
- DriverManager: Manages a list of database drivers and establishes connections
- Connection: Represents an active database session
- Statement / PreparedStatement / CallableStatement: Executes SQL queries
- ResultSet: Holds the data returned by a SELECT query
Q2. Differentiate between Statement and PreparedStatement.
Statement: Executes static SQL strings. The SQL is parsed and compiled every time. Vulnerable to SQL injection when user input is concatenated into the query string.
PreparedStatement: Executes parameterised SQL with ? placeholders. Pre-compiled once and reused with different parameter values. Safe from SQL injection because parameters are treated as data, not SQL code. Also faster for repeated executions due to cached execution plans.
Rule: Always use PreparedStatement for any query involving user input.
Q3. List and explain the four types of JDBC drivers.
Type 1 (JDBC-ODBC Bridge): Translates JDBC calls to ODBC calls. Platform-dependent. Removed in Java 8.
Type 2 (Native-API): Uses database vendor's native client library. Faster than Type 1 but still platform-dependent.
Type 3 (Network Protocol): Sends JDBC calls to a middleware server that translates and forwards to the database. Adds an extra network hop.
Type 4 (Thin/Pure Java): Communicates directly with the database using the DB's network protocol. 100% Java, platform-independent, fastest. Industry standard (e.g., MySQL Connector/J, PostgreSQL JDBC).
Q4. What is SQL injection? How does PreparedStatement prevent it?
SQL Injection: A security attack where an attacker inserts malicious SQL code into user input fields. If the application uses string concatenation to build SQL queries, the injected code executes as part of the SQL statement, potentially dropping tables, stealing data, or bypassing authentication.
Prevention by PreparedStatement: PreparedStatement separates the SQL structure from the data. The SQL template (SELECT * FROM users WHERE name = ?) is compiled first. User input is then bound to the ? placeholder as a data value โ it can never be interpreted as SQL code, even if it contains SQL keywords or special characters.
Q5. Explain transaction management in JDBC with an example.
Transaction management ensures that a group of related database operations either ALL succeed (commit) or ALL fail (rollback), maintaining data consistency.
Steps:
conn.setAutoCommit(false)โ Disable automatic commit- Execute multiple SQL statements
conn.commit()โ Save all changes if everything succeedsconn.rollback()โ Undo all changes if any operation fails (in catch block)
Example: Transferring โน5,000 from Account A to Account B requires two operations: debit A and credit B. If the credit fails after the debit, rollback ensures A's money is restored.
Q6. What is connection pooling? Why is it important?
Connection pooling maintains a pool of pre-created database connections that can be reused across multiple requests. Instead of creating a new connection for each request (expensive: 200โ500ms), applications borrow a connection from the pool and return it when done.
Importance: In a web application handling 1,000 requests/second, creating 1,000 new connections would overwhelm the database. A pool of 20โ50 connections serves all 1,000 requests efficiently. HikariCP is the most popular Java connection pool library and is the default in Spring Boot.
Q7. What is the difference between executeQuery() and executeUpdate()?
executeQuery(): Used for SELECT statements. Returns a ResultSet containing the rows returned by the query.
executeUpdate(): Used for INSERT, UPDATE, DELETE, and DDL (CREATE, ALTER, DROP) statements. Returns an int indicating the number of rows affected.
execute(): Can be used for any SQL statement. Returns a boolean โ true if the result is a ResultSet, false if it's an update count.
Q8. What is a RowSet? How does CachedRowSet differ from ResultSet?
RowSet: A wrapper interface around ResultSet (from javax.sql package) that adds JavaBeans support, scrollability, and disconnected operation.
CachedRowSet vs ResultSet:
- ResultSet requires an active Connection โ if the connection closes, the ResultSet becomes invalid
- CachedRowSet fetches all data into memory and disconnects โ works offline, serialisable, can be passed between layers
- CachedRowSet can also sync changes back to the database when reconnected using
acceptChanges()
Long Answer Questions (3)
Q1. Explain the JDBC architecture in detail with a diagram. Describe the role of each component and how data flows from a Java application to the database and back. (10 marks)
Model Answer:
JDBC follows a 4-tier architecture:
Tier 1 โ Java Application: The developer writes Java code that uses the JDBC API. This could be a standalone app, a servlet, or a Spring Boot service. The application creates SQL queries, sets parameters, and processes results.
Tier 2 โ JDBC API (java.sql / javax.sql): This layer provides standard interfaces (Connection, Statement, PreparedStatement, ResultSet, etc.) that define what operations are possible. The API acts as a contract โ the application codes against these interfaces without knowing the specific database being used.
Tier 3 โ JDBC Driver: The DriverManager class maintains a registry of available drivers. When getConnection(url) is called, it matches the URL pattern to the correct driver. The driver (e.g., mysql-connector-j.jar) implements the JDBC interfaces and translates JDBC calls into the database's native protocol (e.g., MySQL Protocol over TCP/IP).
Tier 4 โ Database: The actual database server (MySQL, Oracle, PostgreSQL) receives the translated commands, parses the SQL, executes it against stored data, and returns results through the same chain in reverse.
Data Flow: Application โ JDBC API โ Driver โ Network โ Database โ Results โ Driver โ JDBC API โ Application (ResultSet)
This layered architecture provides database independence โ changing from MySQL to PostgreSQL requires only changing the driver JAR and connection URL, not the application code.
Q2. Write a complete Java JDBC program that performs all CRUD operations on an Employee table. Explain each operation with proper exception handling and resource management. (15 marks)
Model Answer: The program should include:
- CREATE (INSERT): Use PreparedStatement with setString/setInt/setDouble to insert employee records. Use try-with-resources for automatic resource cleanup.
- READ (SELECT): Execute a parameterised SELECT query. Iterate through ResultSet using while(rs.next()) and extract values using getInt/getString/getDouble with column names.
- UPDATE: Use PreparedStatement with SET clause and WHERE condition. Call executeUpdate() which returns the count of modified rows.
- DELETE: Use PreparedStatement with WHERE clause. Verify affected rows count to confirm deletion.
Key points for full marks:
- Use
try-with-resources(not manual close) - Use
PreparedStatement(not Statement) - Proper
SQLExceptionhandling with meaningful error messages - Close resources in correct order (ResultSet โ Statement โ Connection)
- Use parameterised queries to prevent SQL injection
(Full code provided in Section C, Concept 6 โ reference the InsertBook, SelectBooks, UpdateBook, DeleteBook programs)
Q3. Explain transaction management in JDBC. Write a program that demonstrates commit and rollback with a real-world example of a bank fund transfer. What are ACID properties? (12 marks)
Model Answer:
Transaction Management ensures a group of database operations are treated as a single atomic unit. Either all operations succeed (commit) or all are undone (rollback).
ACID Properties:
- Atomicity: All operations in a transaction complete successfully, or none do
- Consistency: Database moves from one valid state to another โ no constraint violations
- Isolation: Concurrent transactions don't interfere with each other
- Durability: Once committed, changes survive system crashes
JDBC Implementation Steps:
conn.setAutoCommit(false)โ Start manual transaction control- Execute SQL statements (debit from Account A, credit to Account B)
conn.commit()โ Persist changes if all operations succeed- In catch block:
conn.rollback()โ Undo all changes if any operation fails - In finally block:
conn.setAutoCommit(true)โ Restore default behaviour
Real-world importance: Without transactions, a bank transfer could debit โน10,000 from your account but fail to credit the recipient โ losing money. IRCTC uses transactions to ensure ticket booking (seat allocation + payment deduction + PNR generation) is atomic.
(Full code provided in Section C, Concept 7 โ reference the IssueBookTransaction program)
Lab Exercises
All lab exercises for this unit are covered in Section D (Learn by Doing) with the 3-Tier lab structure:
| Tier | Exercise | Duration | Difficulty |
|---|---|---|---|
| ๐ข Tier 1 | Setup MySQL + First JDBC Connection | 60โ90 min | Beginner |
| ๐ก Tier 2 | Complete Library CRUD Application | 90โ120 min | Intermediate |
| ๐ด Tier 3 | Student Marks System with Transactions | 2โ3 hours | Advanced |
Refer to Section D for detailed instructions, hints, and stretch goals for each tier.
Industry Spotlight โ A Day in the Life
๐จโ๐ป Suresh Patel, 31 โ Senior Java Developer at Infosys, Pune
Background: B.Tech from a Tier-3 college in Gujarat. No campus placement. Self-taught Java and JDBC through YouTube and free courses. Built a hospital billing system as a college project using Java + MySQL. Joined Infosys as a fresher through off-campus drive. Now leads a team of 8 developers working on a banking middleware project.
A Typical Day:
9:00 AM โ Standup call with the banking client (SBI). Review JIRA tickets โ today's focus: optimize a slow JDBC query that takes 4 seconds to load 50,000 transaction records.
10:00 AM โ Profile the slow query. Discover the developer used Statement instead of PreparedStatement โ query is being re-parsed on every call. Switch to PreparedStatement: response time drops to 800ms.
11:30 AM โ Code review for a junior developer's module. Find an open Connection that's never closed โ classic connection leak. Add try-with-resources and explain the pattern.
1:00 PM โ Lunch in Infosys cafeteria. Discuss HikariCP connection pool tuning with a colleague โ they're seeing "Connection pool exhausted" errors under peak load.
2:30 PM โ Implement a new feature: batch processing for bulk salary credits. Process 10,000 salary records using addBatch() + executeBatch() with transaction management. If any credit fails, entire batch rolls back.
4:00 PM โ Write JUnit tests for the JDBC DAO layer. Mock the Connection using Mockito. Achieve 85% code coverage.
5:30 PM โ Deploy to staging environment. Run integration tests against a test Oracle database. All green. Push for QA review.
| Detail | Info |
|---|---|
| Tools Used Daily | Java 17, JDBC, HikariCP, Oracle DB, Spring Boot, Maven, JUnit, Git |
| Entry Salary (2024) | โน3.6โ4.5 LPA (Infosys System Engineer) |
| Mid-Level (4โ6 yrs) | โน8โ15 LPA (Technology Lead) |
| Senior (8+ yrs) | โน18โ30 LPA (Technical Architect) |
| Companies Hiring | Infosys, TCS, Wipro, HCL, Cognizant, Capgemini, Oracle India, IBM India, Accenture |
| Key Advice | "Master JDBC before jumping to JPA/Hibernate. Every ORM generates JDBC calls underneath. If you understand JDBC, debugging ORM issues becomes 10x easier." |
Earn With It โ Freelance & Income Roadmap
๐ฐ Your Earning Path After This Unit โ โน10Kโโน40K/month
What you can build: JDBC CRUD applications for small and medium businesses โ inventory systems, billing apps, attendance trackers, library management, student record systems, clinic patient databases.
Why businesses pay: Most small Indian businesses still use pen-and-paper or Excel. A proper database application with search, reports, and backup is worth โน10,000โโน40,000 to them.
| Gig Type | Client | Price Range | Time to Build |
|---|---|---|---|
| Inventory Management System | Kirana store, medical shop, hardware shop | โน10,000โโน20,000 | 1โ2 weeks |
| Billing / Invoice App | Freelancers, small traders, service providers | โน8,000โโน15,000 | 5โ7 days |
| Attendance Tracker | Coaching centres, small offices, gyms | โน5,000โโน12,000 | 3โ5 days |
| Library Management System | School libraries, college departments | โน10,000โโน25,000 | 1โ2 weeks |
| Student Records Database | Coaching centres, tuition classes | โน8,000โโน20,000 | 1 week |
| Clinic Patient Database | Small clinics, dentists, physiotherapy centres | โน15,000โโน40,000 | 2โ3 weeks |
| Platform | Best For | Typical Rate |
|---|---|---|
| Internshala | First freelance projects, college-level clients | โน5,000โโน15,000/project |
| Fiverr | Global clients, quick Java/DB gigs | $30โ$100/gig (โน2,500โโน8,000) |
| Upwork | Serious long-term clients | $15โ$50/hour |
| Local WhatsApp/LinkedIn | Direct outreach to local businesses | โน10,000โโน40,000/project |
โฑ๏ธ Time to First Earning: 3โ4 weeks (if you complete all 3 lab tiers and pitch to 10 local businesses)
Chapter Summary
๐ Unit 14 โ JDBC Database Programming: Key Takeaways
- JDBC = Java Database Connectivity โ the standard API for Java programs to talk to relational databases
- 4-Tier Architecture: Application โ JDBC API โ Driver โ Database
- 5-Step Workflow: Load Driver โ Get Connection โ Create Statement โ Execute โ Process Results โ Close
- 4 Driver Types: Type 1 (ODBC Bridge, obsolete), Type 2 (Native), Type 3 (Network), Type 4 (Pure Java โ use this!)
- 3 Statement Types: Statement (static, vulnerable), PreparedStatement (parameterised, safe), CallableStatement (stored procedures)
- CRUD: INSERT (executeUpdate), SELECT (executeQuery + ResultSet), UPDATE (executeUpdate), DELETE (executeUpdate)
- Transactions: setAutoCommit(false) โ operations โ commit() / rollback() โ ensures ACID properties
- Batch Processing: addBatch() + executeBatch() โ essential for bulk operations
- Connection Pooling: HikariCP โ reuse pre-created connections, avoid per-request overhead
- Security: ALWAYS use PreparedStatement. NEVER concatenate user input into SQL strings.
๐ฆ Code Tweet โ Entire JDBC in 280 Characters
Java โ JDBC in a tweet // JDBC in 5 lines: Connection c = DriverManager.getConnection(url,u,p); PreparedStatement ps = c.prepareStatement("SELECT * FROM t WHERE id=?"); ps.setInt(1,42); ResultSet rs = ps.executeQuery(); while(rs.next()) out.println(rs.getString(1)); // That's it. JavaโSQLโDBโResults. ๐
Earning Checkpoint
| Skill Learned | Tool / Technique | Portfolio Piece | Earn-Ready? |
|---|---|---|---|
| JDBC Connection | DriverManager, Connection | TestConnection.java | โฌ Foundation skill |
| CRUD Operations | PreparedStatement, ResultSet | LibraryCRUD.java | โ Yes โ โน10Kโโน25K/project |
| Transaction Management | commit(), rollback() | IssueBookTransaction.java | โ Yes โ critical for billing apps |
| Batch Processing | addBatch(), executeBatch() | Bulk student import | โ Yes โ data migration gigs |
| SQL Injection Prevention | PreparedStatement | Secure coding knowledge | โ Yes โ interview-ready |
| Connection Pooling | HikariCP (concept) | โ | โฌ Need Spring Boot practice |
| Full Application | Java + MySQL + CRUD | Student Marks System | โ Yes โ โน15Kโโน40K/project |
โ Unit 14 complete. MCQs: 30. Ready for Unit 15: Capstone!
[QR: Link to EduArtha video tutorial โ JDBC Database Programming]