Yandex

SQL with Java
Build School Applications with JDBC



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.

Requirements

  • JDK installed (Java 8+ recommended)
  • MySQL Server (or SQLite for lightweight apps)
  • MySQL JDBC driver (Connector/J)

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();

Best Practices

  • Always close Connection, Statement, and ResultSet
  • Use PreparedStatement to avoid SQL Injection
  • Handle exceptions with try-with-resources (Java 7+)
  • Validate user input before executing queries

Real-World School Use Cases

  • Building a Java-based student record management system
  • Creating admin dashboards for principals
  • Generating attendance and fee reports dynamically
  • Automating admissions using Java GUIs + MySQL

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.

QUIZ

Question 1:Which Java class is primarily used to execute SQL queries?

Question 2:Using `PreparedStatement` in Java helps prevent SQL injection.

Question 3:Which of the following steps are required to connect Java to an SQL database?

Question 4:What does the following Java code print?
Connection con = DriverManager.getConnection(url);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT name FROM students WHERE id = 1");
rs.next();
System.out.println(rs.getString("name"));

Question 5:You must always close ResultSet, Statement, and Connection objects to avoid resource leaks.

Question 6:Which of the following are advantages of using JDBC with Java?



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M