Introduction
Imagine a Java application where teachers can view student marks, administrators can update attendance, and principals can pull reports — all from a simple GUI. That’s the power of combining SQL with Java. This tutorial introduces you to JDBC — Java’s gateway to SQL — using a school management use case.
What is JDBC?
JDBC (Java Database Connectivity) is a Java API that allows you to connect and interact with SQL databases from Java code. It supports SELECT, INSERT, UPDATE, DELETE, and more — all with Java objects.
Step 1: Setup MySQL Database
CREATE DATABASE school;
USE school;
CREATE TABLE students (
roll_no INT PRIMARY KEY,
name VARCHAR(50),
class VARCHAR(10),
city VARCHAR(30)
);
INSERT INTO students VALUES
(1, 'Aarav', '10A', 'Pune'),
(2, 'Diya', '9B', 'Hyderabad');
Step 2: Java Code to Connect and Query
import java.sql.*;
public class StudentDatabase {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/school";
String user = "root";
String password = "your_password";
try {
// Step 1: Load driver (optional in modern Java)
Class.forName("com.mysql.cj.jdbc.Driver");
// Step 2: Create connection
Connection conn = DriverManager.getConnection(url, user, password);
// Step 3: Create statement
Statement stmt = conn.createStatement();
// Step 4: Execute query
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
// Step 5: Process results
while (rs.next()) {
int roll = rs.getInt("roll_no");
String name = rs.getString("name");
String studentClass = rs.getString("class");
String city = rs.getString("city");
System.out.println(roll + " | " + name + " | " + studentClass + " | " + city);
}
// Step 6: Close connection
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
1 | Aarav | 10A | Pune
2 | Diya | 9B | Hyderabad
Step 3: Insert Data with PreparedStatement
String insertSQL = "INSERT INTO students (roll_no, name, class, city) VALUES (?, ?, ?, ?)";
PreparedStatement ps = conn.prepareStatement(insertSQL);
ps.setInt(1, 3);
ps.setString(2, "Sneha");
ps.setString(3, "9A");
ps.setString(4, "Mumbai");
ps.executeUpdate();
Summary
Combining SQL with Java bridges data and application logic — enabling you to build secure, scalable school apps. Whether you’re building a desktop tool for teachers or an attendance tracker for admins, JDBC provides the flexibility to fetch, insert, and manipulate school data in real time.
What’s Next?
Coming up: SQL Interview Questions — practice real-world problems and confidently prepare for database interviews.

About the authorSrinivas Namala
Software Engineer
Srinivas focuses on backend development, databases, systems, and the technologies used to build reliable server-side applications.
View LinkedIn profile ↗