Chapter 24: JDBC (Database Connectivity)

JDBC is the official Java API for connecting to relational databases. It’s been around since Java 1.1 (1997) and is still the foundation of almost every Java backend application in 2026 (Spring Boot, Hibernate, etc. all use JDBC underneath).

We’re going to go super slowly, step by step, like I’m sitting next to you in a quiet Mumbai café, showing you every line of code on my laptop. We’ll cover:

  • Connecting to a database
  • Statement vs PreparedStatement vs CallableStatement
  • Working with ResultSet
  • Complete runnable examples (with MySQL — most common in India)

Important note: To run these examples, you need:

  1. A running MySQL database (local or cloud — I’ll show both)
  2. MySQL Connector/J JAR (the JDBC driver)

0. Setup – One-Time Preparation (Very Important!)

Step 1: Download MySQL Connector/J

  • Go to: https://dev.mysql.com/downloads/connector/j/
  • Download Platform Independent (ZIP) → extract → find mysql-connector-j-9.x.x.jar (or latest 8.x/9.x version)
  • In IntelliJ/Eclipse: Add this JAR to your project libraries (or use Maven — recommended for real projects)

Step 2: Create a Sample Database & Table

Run this SQL in MySQL Workbench or terminal:

SQL

Now let’s write Java code!

1. Connecting to the Database (The Most Important Step)

JDBC URL format (very important!):

text

Common examples:

  • Local MySQL: jdbc:mysql://localhost:3306/java_db
  • With user/password in URL: jdbc:mysql://localhost:3306/java_db?user=root&password=yourpass
  • Modern (recommended): use Properties or DataSource

Step-by-Step Connection Example (2025–2026 style)

Java

Modern & Recommended Way (try-with-resources – auto close!)

Java

2. Statement vs PreparedStatement vs CallableStatement

Type What it is Security (SQL Injection) Performance Use Case
Statement Simple SQL execution Unsafe OK Static queries (rarely used)
PreparedStatement Precompiled SQL + placeholders (?) Safe Best Most common – dynamic queries
CallableStatement Call stored procedures Safe Good Call database procedures/functions

Example 1: Using Statement (NOT recommended for user input!)

Java

Example 2: PreparedStatement (The Modern & Safe Way)

Java

Example 3: CallableStatement (Calling Stored Procedure)

First, create a stored procedure in MySQL:

SQL

Java code:

Java

3. Working with ResultSet (Reading Query Results)

ResultSet is like a cursor pointing to rows returned by a SELECT query.

Important Methods:

Method What it does Example
next() Move to next row (returns false at end) while (rs.next()) { … }
getInt(“column”) / getString(“column”) Get value by column name rs.getString(“name”)
getInt(1) / getString(1) Get value by column index (1-based) rs.getInt(1)
getDate(), getTimestamp() Get date/time values rs.getTimestamp(“created_at”)
wasNull() Check if last column was SQL NULL if (rs.wasNull()) …

Best Practice: Use column names (not indices) — safer when table structure changes.

4. Quick Recap Table (Your Cheat Sheet)

Task Recommended Class / Method Security / Performance Notes
Simple static query Statement Unsafe – avoid for user input
Dynamic query with parameters PreparedStatement (with ?) Safe from SQL injection + fastest
Call stored procedure CallableStatement For complex DB logic
Read results ResultSet + next() Always use try-with-resources
Auto-close resources try-with-resources Prevents leaks

5. Homework for You (Very Practical!)

  1. Basic Write a program that inserts 3 new students into the students table using PreparedStatement.
  2. Medium Write a program that:
    • Asks user for a city name
    • Shows all students from that city
    • Uses PreparedStatement to avoid SQL injection
  3. Advanced Create a method getStudentById(int id) that returns a Student object (make a simple Student class with getters/setters).
  4. Fun Write a program that reads all students and prints them in a nice formatted table (use printf).
  5. Challenge Handle the case when no rows are returned — print “No students found”.

You’re doing fantastic! JDBC is the backbone of almost every Java backend job — now you can connect Java to real databases like a pro.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *