KTU OOP Java2024 Scheme • 60M ESE
MODULE 4/Section 5: JDBC – Theory Only

Common JDBC Components (DriverManager, Connection, Statement, PreparedStatement, CallableStatement, ResultSet) & 6 Connectivity Steps

HIGH PRIORITY (Prep Guide)Official Syllabus + Supplementary~16 min study
Official KTU 2024 Syllabus Topics Covered Here
Steps involved in JDBC connectivityCommon JDBC componentsDriverManagerConnectionStatementPreparedStatementCallableStatementResultSetConnection establishment conceptJDBC execution flow
Java Version Note: Since JDBC 4.0 (Java SE 6), compatible Type 4 drivers are auto-discovered via Java SPI, making explicit Class.forName(...) optional at runtime—though Class.forName(...) remains important for theory exams! Per syllabus rules, this section teaches conceptual theory and connectivity steps ONLY (excluding local DB setup or CRUD lab projects).

1. Topic Introduction

Whether a Java program talks to MySQL, PostgreSQL, or Oracle, every database interaction uses the exact same core interfaces in java.sql and follows the exact same 6-step JDBC connectivity lifecycle. Mastering the role of each component (DriverManager, Connection, Statement vs PreparedStatement vs CallableStatement, ResultSet, SQLException) and drawing the 6-step sequence secures full marks on Module 4's final Part B section.

2. Start From Zero: Calling a Restaurant (DriverManager -> Connection), Writing an Order (Statement) & Reading the Receipt (ResultSet)

Imagine ordering food by phone: (1) Open the phonebook (import java.sql.*); (2) Load the phone dialer (Register Driver); (3) Dial and keep an open call line (DriverManager.getConnection() returns a **Connection); (4) Hand your order to a waiter (Statement for one-off orders, PreparedStatement for pre-printed fill-in-the-blank templates, CallableStatement for chef-special stored procedures); (5) Read the returned menu items row-by-row (ResultSet** cursor rs.next()); (6) Hang up the call (close() resources)!

Key Takeaway: 6 Steps: 1. Import java.sql.* -> 2. Register Driver -> 3. Open Connection -> 4. Execute Statement -> 5. Extract ResultSet -> 6. Close Resources.

3. Essential Exam Definitions

DriverManager (Class) & Driver (Interface)
DriverManager manages registered Driver implementations and matches a connection request's JDBC URL subprotocol to the first compatible driver to return a Connection.
Connection (Interface)
Represents a live communication session (physical context) with a specific database; factory for creating Statement, PreparedStatement, and CallableStatement objects (conn.createStatement(), conn.close()).
Statement vs PreparedStatement vs CallableStatement
Statement executes static SQL strings compiled every call; PreparedStatement (sub-interface) executes precompiled parameterized SQL with ? placeholders (prevents SQL injection & runs faster repeatedly); CallableStatement invokes database Stored Procedures.
ResultSet (Interface) & SQLException (Class)
ResultSet holds tabular data returned by executeQuery() and acts as a cursor iterator (rs.next(), rs.getInt(), rs.getString()). SQLException is a checked exception class reporting database/SQL errors.

4. Detailed Technical Explanation & Syntax

1. Common JDBC Components (Roles & Hierarchy)

Notice that DriverManager and SQLException are concrete classes, whereas Driver, Connection, Statement, PreparedStatement, CallableStatement, and ResultSet are Interfaces implemented by each vendor's JDBC driver (Dependency Inversion Principle in action!).

Key Statement Execution Methods: executeQuery(sql) returns a ResultSet (used for SELECT); executeUpdate(sql) returns an int row count (used for INSERT/UPDATE/DELETE); execute(sql) returns boolean (general execution).

2. The Six Conceptual Steps Involved in JDBC Connectivity

Write these six steps in exact order in KTU 6-mark / 9-mark answers:

  • Step 1 — Import Required Packages: import java.sql.*; brings JDBC interfaces/classes into scope.
  • Step 2 — Load & Register JDBC Driver: Class.forName("com.mysql.cj.jdbc.Driver"); initializes the driver class with DriverManager (automatic since JDBC 4.0).
  • Step 3 — Open a Connection: Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); opens the communication session.
  • Step 4 — Create & Execute Statement: Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); (or conn.prepareStatement(...)).
  • Step 5 — Extract Data from ResultSet: Loop cursor while (rs.next()) and read typed columns via rs.getInt("id"), rs.getString("name").
  • Step 6 — Clean Up / Close Resources: Explicitly close rs.close(), stmt.close(), and conn.close() inside a finally block (or try-with-resources) rather than waiting for Garbage Collection.

5. Working Principle: Why PreparedStatement Improves Security & Performance

  1. 1. PreparedStatement ps = conn.prepareStatement("SELECT name FROM Student WHERE id = ?"); sends the template to the DB once to precompile the query execution plan.
  2. 2. Binding ps.setInt(1, 105); treats user input strictly as typed data—preventing SQL Injection attacks and avoiding repeated SQL parsing.

6. Examination-Ready Diagrams

Diagram 20

6-Step JDBC Connectivity Execution Sequence

1. Import java.sql.*Load JDBC API interfaces2. Register DriverClass.forName(...) / SPI Auto3. Open ConnectionDriverManager.getConnection()4. Execute StatementcreateStatement().executeQuery()5. Read ResultSetwhile (rs.next()) rs.getXXX()6. Clean Up Resourcesrs.close(), stmt.close(), conn.close()

Sequential flowchart of the six conceptual JDBC steps from importing java.sql.* to closing database resources.

Key Components
  • Step 1: Import Packages: import java.sql.*; brings JDBC interfaces/classes into scope.
  • Step 2: Register Driver: Class.forName(...) (or automatic SPI loading since JDBC 4.0).
  • Step 3: Open Connection: DriverManager.getConnection(url, user, pass) returns Connection.
  • Step 4: Create & Execute Statement: conn.createStatement() / prepareStatement(), then executeQuery() or executeUpdate().
  • Step 5: Process ResultSet: Iterate cursor with while(rs.next()) and rs.getInt()/rs.getString().
  • Step 6: Close Resources: Explicitly close ResultSet, Statement, and Connection (or try-with-resources).
Step-by-Step Flow
  1. Import java.sql.* -> Load/Register Driver -> Obtain Connection -> Create Statement -> Execute SQL -> Read ResultSet -> Close rs, stmt, conn.
How to Draw in KTU Exam
  • Draw 6 numbered sequential boxes connected by downward/rightward arrows with the exact method call inside each box: import java.sql.* -> Class.forName() -> DriverManager.getConnection() -> createStatement() / executeQuery() -> rs.next() / rs.getXXX() -> close().

7. Complete Java Code Examples & Tracing

Conceptual 6-Step JDBC Connectivity Skeleton (Theory Reference Only)JdbcConnectivityTemplate.java
Illustrates all 6 conceptual JDBC steps (import, Class.forName, DriverManager.getConnection, Statement, ResultSet, finally cleanup) cleanly without requiring a live local DB server.
1import java.sql.*; // Step 1: Import JDBC API
2
3public class JdbcConnectivityTemplate {
4 // Conceptual method demonstrating the 6 theoretical steps of JDBC connectivity
5 public static void demonstrateSteps(String driverClass, String dbUrl, String user, String pass) {
6 Connection conn = null;
7 Statement stmt = null;
8 ResultSet rs = null;
9
10 try {
11 // Step 2: Load/Register Driver (optional in JDBC 4.0+ via SPI)
12 Class.forName(driverClass);
13
14 // Step 3: Establish physical Connection via DriverManager
15 conn = DriverManager.getConnection(dbUrl, user, pass);
16
17 // Step 4: Create Statement & submit query
18 stmt = conn.createStatement();
19 rs = stmt.executeQuery("SELECT id, name FROM Student");
20
21 // Step 5: Navigate ResultSet cursor & extract columns
22 while (rs.next()) {
23 int id = rs.getInt("id");
24 String name = rs.getString("name");
25 System.out.println("ID: " + id + ", Name: " + name);
26 }
27 } catch (ClassNotFoundException e) {
28 System.out.println("Conceptual Demo -> Driver not attached on classpath: " + e.getMessage());
29 } catch (SQLException e) {
30 System.out.println("Database connectivity error: " + e.getMessage());
31 } finally {
32 // Step 6: Explicitly close ResultSet, Statement, and Connection
33 try { if (rs != null) rs.close(); } catch (SQLException ignored) {}
34 try { if (stmt != null) stmt.close(); } catch (SQLException ignored) {}
35 try { if (conn != null) conn.close(); } catch (SQLException ignored) {}
36 }
37 }
38
39 public static void main(String[] args) {
40 System.out.println("=== JDBC 6-Step Connectivity Flow (Theory Demo) ===");
41 demonstrateSteps("com.example.DemoJdbcDriver", "jdbc:demo://localhost:3306/ktu", "student", "pass");
42 }
43}
Expected Output
=== JDBC 6-Step Connectivity Flow (Theory Demo) ===
Conceptual Demo -> Driver not attached on classpath: com.example.DemoJdbcDriver
Keywords:DriverManagerConnectionStatementPreparedStatementCallableStatementResultSetSQLException
Common Exam & Coding Mistakes
  • Trying to read rs.getInt() BEFORE calling rs.next() (ResultSet cursor initially starts before row 1!).
  • Forgetting to close Connection/Statement/ResultSet in finally (causes connection leaks).
  • Using executeQuery() for INSERT/UPDATE instead of executeUpdate().

Comparison Tables

Statement vs PreparedStatement vs CallableStatement
FeatureStatementPreparedStatementCallableStatement
InheritanceBase interfaceExtends StatementExtends PreparedStatement
Primary UseStatic one-time SQL queriesParameterized repeated queries (?)Calling DB Stored Procedures ({call ...})
CompilationCompiled on DBMS every executionPrecompiled once on DB server (faster)Precompiled stored procedure on DB
SQL Injection SafetyVulnerable if string concatenatedSafe (parameters bound securely via setString/setInt)Safe via parameter binding

Real-World Applications

  • University examination portals, banking ledgers, and enterprise backend services rely on JDBC interfaces beneath higher-level libraries.

Important KTU Exam Points

  • Write ALL 6 JDBC Steps clearly in order AND draw Diagram 20!
  • Always include Statement vs PreparedStatement vs CallableStatement comparison—frequently asked for 3 or 6 marks.

Memory Techniques & Revision

  • 6 JDBC Steps — 'I-R-O-E-E-C': Import (java.sql.*) -> Register (Class.forName) -> Open (getConnection) -> Execute (Statement) -> Extract (ResultSet) -> Close (finally).

Common Pitfalls to Avoid

  • Mixing up Step 2 (Class.forName) and Step 3 (DriverManager.getConnection), or omitting Step 6 resource cleanup.

KTU-Style Questions & Exam-Ready Answers

Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.

Introduction: Establishing database connectivity and retrieving data in Java via JDBC follows a standardized six-step conceptual workflow using java.sql components.

  • Step 1: Import JDBC packages (import java.sql.*;).
  • Step 2: Register the JDBC Driver (Class.forName("..."); automatic in JDBC 4.0+).
  • Step 3: Open a Connection (DriverManager.getConnection(url, user, pass) returns Connection).
  • Step 4: Execute a Query (conn.createStatement() / prepareStatement(), calling executeQuery() or executeUpdate()).
  • Step 5: Extract Data from ResultSet (while (rs.next()) with rs.getInt(), rs.getString()).
  • Step 6: Clean Up Resources (rs.close(), stmt.close(), conn.close() in finally).
Exam Diagram Note: Reproduce Diagram 20 (6-Step JDBC Sequence) and briefly summarize DriverManager, Connection, Statement, and ResultSet.

Quick Understanding Check

1. Which JDBC interface represents a precompiled parameterized SQL statement with ? placeholders?

2. What is the correct order of the core JDBC workflow?