SQL with Java — Build School Applications with JDBC

SQL with Java

A school application needs a class report based on a user-selected class without treating that input as SQL syntax.

JDBC is Java’s database access API. A suitable database driver supplies connections, statements and result sets for the selected engine.

  1. Explain and apply

    Bind values with JDBC, read the returned rows and release database resources.

  2. Work it out

    Design a JDBC statement with a bound class value, then predict the two returned names for 10A.

  3. Avoid mistakes

    A driver must be installed and compatible with the server.

SQL with Java: the request and its result

  1. School need

    A school application needs a class report based on a user-selected class without treating that input as SQL syntax.

  2. Database operation

    JDBC is Java’s database access API. A suitable database driver supplies connections, statements and result sets for the selected engine.

  3. Check the outcome

    The SQL-level behavior is verified with the practice fixture. In Java, setString(1, "10A") binds the first parameter; the preserved JDBC examples require the specified driver and live server.

A conceptual model. The query examples below show the actual syntax, input data and results.

Understand what the database does

Use PreparedStatement with a question-mark value placeholder, bind values using the appropriate setter, then execute and read ResultSet rows. JDBC parameter indexes start at one. Try-with-resources closes connections, statements and result sets that are included in its resource declaration.

Related concepts: Prevent SQL Injection and Transactions and Connect with JDBC and ODBC.

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

SQL · portable concepts; preserved examples identify their engine

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

Java · JDBC

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

Java · JDBC

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

Query discussed in this section:

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

Important differences and mistakes

A driver must be installed and compatible with the server. Closing resources is not a substitute for choosing transaction boundaries when auto-commit is disabled. Keep credentials in configuration and verify the driver’s TLS settings rather than copying insecure connection flags.

Try it with the school data

Design a JDBC statement with a bound class value, then predict the two returned names for 10A.

This practice uses a separate, fresh fixture named practice_students. It does not continue the changing table state of the earlier examples.

Practice input: practice_students
roll_nonameclassmarkscity
1Aarav10A85Pune
2Diya9B70Chennai
3Sneha10A85Pune

SQL · create only these practice tables in a disposable database:

CREATE TABLE practice_students (roll_no INTEGER PRIMARY KEY, name VARCHAR(50), class VARCHAR(10), marks INTEGER, city VARCHAR(30));
INSERT INTO practice_students VALUES
(1, 'Aarav', '10A', 85, 'Pune'),
(2, 'Diya', '9B', 70, 'Chennai'),
(3, 'Sneha', '10A', 85, 'Pune');

Worked answer and reasoning

This practice uses a separate, fresh fixture named practice_students. It does not continue the changing table state of the earlier examples.

Practice input: practice_students
roll_nonameclassmarkscity
1Aarav10A85Pune
2Diya9B70Chennai
3Sneha10A85Pune

SQL · create only these practice tables in a disposable database:

CREATE TABLE practice_students (roll_no INTEGER PRIMARY KEY, name VARCHAR(50), class VARCHAR(10), marks INTEGER, city VARCHAR(30));
INSERT INTO practice_students VALUES
(1, 'Aarav', '10A', 85, 'Pune'),
(2, 'Diya', '9B', 70, 'Chennai'),
(3, 'Sneha', '10A', 85, 'Pune');

SQL · this practice variation runs with SQLite 3; the preserved examples retain their stated dialect

Bind the value "10A" through the driver’s parameter API. The question mark is a parameter marker, not literal SQL text to replace with string concatenation.

SELECT name FROM practice_students WHERE class = ? ORDER BY roll_no;
Expected query result
name
Aarav
Sneha

The SQL-level behavior is verified with the practice fixture. In Java, setString(1, "10A") binds the first parameter; the preserved JDBC examples require the specified driver and live server.

Check your understanding

Which parameter index binds the first JDBC question-mark value?
Choose one answer. You can try again.

Answer and explanation

1.

The SQL-level behavior is verified with the practice fixture. In Java, setString(1, "10A") binds the first parameter; the preserved JDBC examples require the specified driver and live server.

Use the idea independently

JDBC is Java’s database access API. A suitable database driver supplies connections, statements and result sets for the selected engine.

The SQL-level behavior is verified with the practice fixture. In Java, setString(1, "10A") binds the first parameter; the preserved JDBC examples require the specified driver and live server.

Continue your understanding with Prevent SQL Injection and Transactions and Connect with JDBC and ODBC.

Source for the engine-specific behavior: MySQL Connector/J documentation.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: SQL with Excel — Query Your School Data Without Leaving Excel →