Skip to lesson

JDBC, PreparedStatement and SQL Injection

Even if ShopLite uses Spring Data JPA, interviewers still ask how plain JDBC works, and SQL injection is one of the most asked security questions. They check that you know the steps in order and can say why a PreparedStatement is safe.

The JDBC steps in order

JDBC (Java Database Connectivity) is the standard Java API in java.sql for connecting to a relational database, running SQL and reading the results. Each database vendor supplies a driver that implements it.

Interviewers want the steps in order, from the connection to the cleanup. Each step is numbered in a comment of this example.

Example 1 · The JDBC steps, numbered in the code

Runs in: a Maven project with the MySQL JDBC driver and a ShopLite-style database (Section 13)

RJdbcSteps.javaJava
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;
public class RJdbcSteps {    public static void main(String[] args) {        String url = "jdbc:mysql://localhost:3306/shoplite";        String sql = "SELECT name, price FROM products WHERE price < ? ORDER BY price";
        try (Connection con = DriverManager.getConnection(url, "shop_app", System.getenv("DB_PASSWORD")); // 2. connect             PreparedStatement ps = con.prepareStatement(sql)) {            ps.setBigDecimal(1, new BigDecimal("500"));            try (ResultSet rs = ps.executeQuery()) { // 5. execute                while (rs.next()) {                    System.out.println(rs.getString("name") + " - Rs " + rs.getBigDecimal("price"));                }            }        } catch (SQLException e) {            System.out.println("DB error " + e.getSQLState() + ": " + e.getMessage());        } // 8. resources closed automatically    }}
Sample output
Pen - Rs 20.00
Notebook - Rs 55.00
Calculator - Rs 450.00

What this code does

  • Three steps are marked with a number; the others are the calls themselves: prepareStatement (3), setBigDecimal (4), while (rs.next()) (6) and catch (SQLException e) (7). Both Connection and PreparedStatement are opened in one try-with-resources header, and the ResultSet in a nested one, so all three close automatically.
  • ps.setBigDecimal(1, ...) binds the first ? (indexes start at 1). The output depends on your products table; this run had four products, one of them above Rs 500.

executeQuery runs a SELECT and returns a ResultSet; executeUpdate runs INSERT, UPDATE or DELETE and returns the row count. rs.next() moves to the next row and returns false after the last one. Indexes in setX(1, ...) and getX(1) start at 1. Since JDBC 4 the driver registers itself, so Class.forName(...) is not needed. Read passwords from environment variables, never from the code.

Revise: What is JDBC (opens in a new tab), Reading a ResultSet (opens in a new tab).

Order of execution

The JDBC steps

Put the steps in the order a JDBC program runs them.

Statement vs PreparedStatement, and how SQL injection works

SQL injection is an attack where user input is pasted into SQL text and changes what the query means. A PreparedStatement prevents it by sending the SQL and the values separately.

The classic question: what does ' OR '1'='1 do to a login query? The first example prints the SQL that string joining builds; the second compares both JDBC styles.

Two ways to send the text ' OR '1'='1 as a password. Joined with plus, it becomes part of the SQL, so every row matches. With a ? placeholder, the SQL keeps its shape and the text travels apart as a value, so no user matches.

Example 2 · What string concatenation turns into

InjectionStringDemo.javaJava
public class InjectionStringDemo {    static String unsafeQuery(String email, String password) {        return "SELECT * FROM users WHERE email = '" + email + "' AND password_hash = '" + password + "'";    }
    public static void main(String[] args) {        System.out.println("Normal input:");        System.out.println(unsafeQuery("asha@clg.in", "x9Lq"));
        System.out.println("Attacker types  ' OR '1'='1  as the password:");        System.out.println(unsafeQuery("asha@clg.in", "' OR '1'='1"));
        System.out.println("Attacker types  asha@clg.in'--  as the email:");        System.out.println(unsafeQuery("asha@clg.in'-- ", "anything"));
        System.out.println("PreparedStatement keeps the SQL fixed:");        System.out.println("SELECT * FROM users WHERE email = ? AND password_hash = ?");        System.out.println("parameter 2 is sent as a value: [' OR '1'='1]");    }}
Output
Normal input:
SELECT * FROM users WHERE email = 'asha@clg.in' AND password_hash = 'x9Lq'
Attacker types  ' OR '1'='1  as the password:
SELECT * FROM users WHERE email = 'asha@clg.in' AND password_hash = '' OR '1'='1'
Attacker types  asha@clg.in'--  as the email:
SELECT * FROM users WHERE email = 'asha@clg.in'-- ' AND password_hash = 'anything'
PreparedStatement keeps the SQL fixed:
SELECT * FROM users WHERE email = ? AND password_hash = ?
parameter 2 is sent as a value: [' OR '1'='1]

What this code does

  • With the input ' OR '1'='1, the WHERE clause becomes ... password_hash = '' OR '1'='1', which is true for every row. With asha@clg.in'-- , everything after -- is a comment, so the password check disappears.
  • With a PreparedStatement the SQL text never changes; the attacker's text is just a strange password value that matches nothing.

Example 3 · Statement vs PreparedStatement against the same attack

Runs in: a Maven project with the MySQL JDBC driver and a ShopLite-style database (Section 13)

RLoginDao.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class RLoginDao {    // Vulnerable: user input becomes part of the SQL text    static boolean loginUnsafe(Connection con, String email, String hash) throws SQLException {        String sql = "SELECT COUNT(*) FROM users WHERE email = '" + email + "' AND password_hash = '" + hash + "'";        try (Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql)) {            rs.next();            return rs.getInt(1) > 0;        }    }
    // Safe: SQL is compiled first; inputs are bound as values    static boolean loginSafe(Connection con, String email, String hash) throws SQLException {        String sql = "SELECT COUNT(*) FROM users WHERE email = ? AND password_hash = ?";        try (PreparedStatement ps = con.prepareStatement(sql)) {            ps.setString(1, email);            ps.setString(2, hash);            try (ResultSet rs = ps.executeQuery()) {                rs.next();                return rs.getInt(1) > 0;            }        }    }
    static void demo(Connection con) throws SQLException {        String attack = "' OR '1'='1";        System.out.println("unsafe login with attack: " + loginUnsafe(con, "asha@clg.in", attack));        System.out.println("safe login with attack:   " + loginSafe(con, "asha@clg.in", attack));    }
    public static void main(String[] args) throws SQLException {        try (Connection con = DriverManager.getConnection(                "jdbc:mysql://localhost:3306/shoplite", "shop_app", System.getenv("DB_PASSWORD"))) {            demo(con);        }    }}
Sample output
unsafe login with attack: true
safe login with attack:   false

What this code does

  • loginUnsafe builds the SQL with +, so the attack makes the count non-zero and the login succeeds without the password.
  • loginSafe uses ? placeholders and setString; the database compares the whole attack text as a password value, finds no match, and returns false.

A PreparedStatement sends the SQL with ? placeholders first, where it is parsed and fixed; the inputs follow as values. Placeholders work for values only, not for table or column names: check those against a whitelist. For LIKE, bind "%" + text + "%" as the value. JPA is safe with :name parameters and unsafe if you join JPQL strings.

Revise: SQL injection demonstrated (opens in a new tab), PreparedStatement and placeholders (opens in a new tab).

Find the bug

Find the unsafe line

One line in each snippet is wrong. Click it.

This login lets an attacker in with the password ' OR '1'='1. Which line?

Round 1 of 3

try-with-resources and connection pooling

A connection pool keeps a few database connections open and lends them to requests, because opening a connection is slow. HikariCP is Spring Boot's default pool; close() on a pooled connection returns it to the pool.

Connections, statements and result sets must be closed even when an exception is thrown. This example uses a fake resource to show the order.

Example 4 · try-with-resources closes in reverse order, even on errors

CloseOrderDemo.javaJava
class FakeResource implements AutoCloseable {    private final String name;
    FakeResource(String name) {        this.name = name;        System.out.println("open  " + name);    }
    @Override    public void close() {        System.out.println("close " + name);    }}
public class CloseOrderDemo {    public static void main(String[] args) {        try (FakeResource con = new FakeResource("Connection");             FakeResource ps = new FakeResource("PreparedStatement");             FakeResource rs = new FakeResource("ResultSet")) {            System.out.println("reading rows...");            throw new IllegalStateException("column not found");        } catch (IllegalStateException e) {            System.out.println("caught after closing: " + e.getMessage());        }    }}
Output
open  Connection
open  PreparedStatement
open  ResultSet
reading rows...
close ResultSet
close PreparedStatement
close Connection
caught after closing: column not found

What this code does

  • The three resources open in order and close in reverse (result set, statement, connection) before the catch block runs, even though the body threw an exception.
  • With a real pool, the connection's close() returns it to the pool; without try-with-resources an exception would skip the close and leak it.

Connection, Statement and ResultSet all implement AutoCloseable, so try-with-resources closes them in reverse order of opening. Forgetting to close leaks connections until the pool or the database refuses new ones. A DataSource is the factory that frameworks inject instead of calling DriverManager.

Revise: try-with-resources (opens in a new tab), Why connection pooling (opens in a new tab), HikariCP setup (opens in a new tab).

Predict the output

When does each resource close?

Predict the printed list.

Round 1 of 2

What does this program print?

import java.util.ArrayList;
import java.util.List;
public class CloseOrder {
static List<String> log = new ArrayList<>();
record Res(String name) implements AutoCloseable {
Res { log.add("open " + name); }
public void close() { log.add("close " + name); }
}
public static void main(String[] args) {
try (Res con = new Res("con"); Res ps = new Res("ps")) {
log.add("run");
}
System.out.println(log);
}
}

Transactions: setAutoCommit(false), commit, rollback

Auto-commit is the JDBC default where every statement commits as soon as it runs. For statements that must succeed together, call setAutoCommit(false), run them, then commit(), or rollback() when something fails.

A money transfer needs the debit and the credit to commit together. This example turns auto-commit off, rolls back when the balance is too low, and restores the setting.

Example 5 · A JDBC transaction: commit both updates or roll back both

Runs in: a Maven project with the MySQL JDBC driver and a ShopLite-style database (Section 13)

RTransfer.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;
public class RTransfer {    static void transfer(Connection con, int from, int to, int amount) throws SQLException {        String debit = "UPDATE wallets SET balance = balance - ? WHERE id = ? AND balance >= ?";        String credit = "UPDATE wallets SET balance = balance + ? WHERE id = ?";        boolean oldAutoCommit = con.getAutoCommit();        con.setAutoCommit(false);            try (PreparedStatement d = con.prepareStatement(debit);             PreparedStatement c = con.prepareStatement(credit)) {            d.setInt(1, amount);            d.setInt(2, from);            d.setInt(3, amount);            if (d.executeUpdate() != 1) {                throw new SQLException("Insufficient balance in wallet " + from);            }            c.setInt(1, amount);            c.setInt(2, to);            c.executeUpdate();            con.commit();                                  // both updates, or ...            System.out.println("Transferred Rs " + amount);        } catch (SQLException e) {            con.rollback();                                // ... neither            System.out.println("Rolled back: " + e.getMessage());        } finally {            con.setAutoCommit(oldAutoCommit);              // pooled connections are reused        }    }
    public static void main(String[] args) throws SQLException {        try (Connection con = DriverManager.getConnection(                "jdbc:mysql://localhost:3306/shoplite", "shop_app", System.getenv("DB_PASSWORD"))) {            transfer(con, 1, 2, 300);            transfer(con, 1, 2, 5000);        }    }}
Sample output
Transferred Rs 300
Rolled back: Insufficient balance in wallet 1

What this code does

  • Auto-commit is turned off, so the debit and credit form one transaction. The first transfer commits. The second finds too little money (executeUpdate returns 0 rows), throws, and rollback() undoes everything.
  • The finally block restores the old auto-commit setting, because with a pool the next user gets this same connection.

Restore auto-commit in finally, because pooled connections are reused. A Savepoint rolls back part of a transaction, batching (addBatch, executeBatch) sends many statements in one round trip, and setTransactionIsolation sets the isolation level. In Spring, @Transactional does the commit and rollback for you.

Revise: Commit and rollback (opens in a new tab), JDBC batch inserts (opens in a new tab).

Fix the error

Fix the real compiler error

Read the javac error, then pick the line that fixes it.

Round 1 of 2

pay turns auto-commit off. Fix the header so the method compiles.

import java.sql.Connection;
import java.sql.SQLException;
public class FixCommit {
static void pay(Connection con) {
con.setAutoCommit(false);
}
}

Error

FixCommit.java:6: error: unreported exception SQLException; must be caught or declared to be thrown
        con.setAutoCommit(false);
                         ^

The DAO pattern

A DAO (Data Access Object) is a class that hides all database code for one entity behind an interface, so the service layer never sees SQL, Connection or ResultSet.

The service asks a StudentDao for students and never writes SQL. This example plugs in an in-memory implementation.

Example 6 · DAO: the service talks to an interface, not to SQL

DaoPatternDemo.javaJava
import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Optional;
record Student(int roll, String name, String branch) {}
interface StudentDao {                                     // what the rest of the app sees    Optional<Student> findByRoll(int roll);    List<Student> findByBranch(String branch);    void save(Student s);}
class InMemoryStudentDao implements StudentDao {           // a JdbcStudentDao would use SQL here    private final Map<Integer, Student> table = new LinkedHashMap<>();
    public Optional<Student> findByRoll(int roll) {        return Optional.ofNullable(table.get(roll));    }
    public List<Student> findByBranch(String branch) {        List<Student> result = new ArrayList<>();        for (Student s : table.values()) {            if (s.branch().equals(branch)) result.add(s);        }        return result;    }
    public void save(Student s) {        table.put(s.roll(), s);    }}
class StudentService {                                     // business logic, no SQL    private final StudentDao dao;
    StudentService(StudentDao dao) {        this.dao = dao;    }
    String greet(int roll) {        return dao.findByRoll(roll).map(s -> "Hello " + s.name()).orElse("No student " + roll);    }}
public class DaoPatternDemo {    public static void main(String[] args) {        StudentDao dao = new InMemoryStudentDao();        dao.save(new Student(1, "Asha", "CSE"));        dao.save(new Student(2, "Ravi", "ECE"));        dao.save(new Student(3, "Meena", "CSE"));
        StudentService service = new StudentService(dao);        System.out.println(service.greet(2));        System.out.println(service.greet(9));        System.out.println("CSE: " + dao.findByBranch("CSE"));    }}
Output
Hello Ravi
No student 9
CSE: [Student[roll=1, name=Asha, branch=CSE], Student[roll=3, name=Meena, branch=CSE]]

What this code does

  • StudentService depends only on StudentDao. Here an in-memory implementation is plugged in; a JdbcStudentDao with PreparedStatements could replace it without changing the service.
  • This is why DAOs make unit tests easy: pass a fake DAO and test the business logic without a database.

Model answer: "A DAO separates persistence from business logic. I can swap JDBC for JPA, or an in-memory fake for unit tests, without touching the service. In Spring Data JPA the repository interfaces play the DAO role."

Revise: DAO interface and JDBC implementation (opens in a new tab), Swapping DAO implementations (opens in a new tab).

Next step

Check your understanding

12 quick questions