Skip to lesson

Setting parameters of each type

A price stored as a double can drift by a fraction of a paisa, and a missing phone number cannot simply be saved as empty text. Every kind of column needs the matching set method.

Numbers, money and booleans

setBigDecimal(index, value) fills a placeholder with a BigDecimal, the Java type for money. It pairs with a DECIMAL(10,2) column, so prices stay exact.

Match the method to the column: setInt for an INT id, setLong for a long, setBigDecimal for a DECIMAL price and setBoolean for yes or no. Example 1 filters products by price range and active flag.

Example 1 · setBigDecimal and setBoolean in a filter

Runs in: a Maven project with the MySQL driver and the ShopLite database

PriceRangeFilter.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 PriceRangeFilter {    public static void main(String[] args) throws SQLException {        String sql = "SELECT name, price FROM products"                + " WHERE price BETWEEN ? AND ? AND is_active = ? ORDER BY price";        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));             PreparedStatement ps = con.prepareStatement(sql)) {            ps.setBigDecimal(1, new BigDecimal("1000.00"));            ps.setBigDecimal(2, new BigDecimal("3000.00"));            ps.setBoolean(3, true);            try (ResultSet rs = ps.executeQuery()) {                while (rs.next()) System.out.println(rs.getString(1) + " Rs " + rs.getBigDecimal(2));            }        }    }}
Output
boAt Airdopes 141 Rs 1299.00
Prestige Pressure Cooker 3L Rs 1899.00
Mi Power Bank 20000mAh Rs 2199.00
Running Shoes Rs 2499.00

What this code does

  • The two money bounds use setBigDecimal, and the active flag uses setBoolean. Each method matches its column type.
  • BETWEEN ? AND ? keeps both bounds as parameters, so the filter is safe and reads clearly.

Money is always BigDecimal, never double: a price like 17999.00 kept as a double can drift by a fraction of a paisa.

Dates and times with setObject

setObject(index, value) fills a placeholder with any Java value. For dates and times it takes a java.time object, and the driver converts it to the column's type.

For a DATE, DATETIME or TIMESTAMP column, bind a java.time value with setObject(index, value). Example 2 counts the orders placed since 1 September.

Example 2 · A date bound with setObject

Runs in: a Maven project with the MySQL driver and the ShopLite database

OrdersSince.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.time.LocalDate;import java.time.LocalDateTime;
public class OrdersSince {    public static void main(String[] args) throws SQLException {        String sql = "SELECT COUNT(*) FROM orders WHERE ordered_at >= ?";        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));             PreparedStatement ps = con.prepareStatement(sql)) {            LocalDateTime since = LocalDate.of(2026, 9, 1).atStartOfDay();            ps.setObject(1, since);            try (ResultSet rs = ps.executeQuery()) {                rs.next();                System.out.println("Orders since " + since + ": " + rs.getInt(1));            }        }    }}
Output
Orders since 2026-09-01T00:00: 6

What this code does

  • ordered_at is a DATETIME, so the bound value is a LocalDateTime. atStartOfDay() turns 1 September into that day at 00:00.
  • setObject hands the java.time value to the driver, which converts it. No java.sql.Timestamp is needed.

A LocalDate matches a DATE column; a LocalDateTime matches DATETIME or TIMESTAMP. The old setDate and setTimestamp take the legacy java.sql.Date and java.sql.Timestamp classes, which you rarely need today.

Optional values with setNull

setNull(index, type) stores a SQL NULL through a placeholder. The type is a constant from java.sql.Types, such as Types.VARCHAR, so the driver knows the column's type.

When a value is missing and the column allows NULL, call setNull(index, type). Example 3 saves a customer without a phone number and reads the row back.

Example 3 · setNull for a missing phone number

Runs in: a Maven project with the MySQL driver and the ShopLite database

OptionalPhone.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Types;
public class OptionalPhone {    static int addCustomer(Connection con, String name, String email, String phone) throws SQLException {        String sql = "INSERT INTO customers (full_name, email, phone) VALUES (?, ?, ?)";        try (PreparedStatement ps = con.prepareStatement(sql)) {            ps.setString(1, name);            ps.setString(2, email);            if (phone == null) {                ps.setNull(3, Types.VARCHAR);            } else {                ps.setString(3, phone);            }            return ps.executeUpdate();        }    }
    public static void main(String[] args) throws SQLException {        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) {            con.setAutoCommit(false);            addCustomer(con, "Ola Behera", "ola.behera@example.com", null);
            String read = "SELECT full_name, phone FROM customers WHERE email = ?";            try (PreparedStatement ps = con.prepareStatement(read)) {                ps.setString(1, "ola.behera@example.com");                try (ResultSet rs = ps.executeQuery()) {                    rs.next();                    String name = rs.getString("full_name");                    String phone = rs.getString("phone");                    boolean missing = rs.wasNull();                    System.out.println(name + " phone=" + phone + " wasNull=" + missing);                }            }            con.rollback();        }    }}
Output
Ola Behera phone=null wasNull=true

What this code does

  • The phone is missing, so setNull(3, Types.VARCHAR) stores a real SQL NULL in the text column.
  • On read, getString returns null and wasNull() is true. Call wasNull() right after reading the column, before reading another one.

Passing setString(index, null) often works too, but setNull states the intent and the column type clearly.

LIKE searches: the % goes in the value

In a LIKE search, the wildcards % (any text) and _ (one character) belong in the bound value, not in the SQL. Example 4 writes LIKE ? and binds "%" + term + "%".

Example 4 · A safe LIKE search

Runs in: a Maven project with the MySQL driver and the ShopLite database

LikeSearch.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;
public class LikeSearch {    static void search(Connection con, String term) throws SQLException {        String sql = "SELECT name FROM products WHERE name LIKE ? ORDER BY name";        try (PreparedStatement ps = con.prepareStatement(sql)) {            ps.setString(1, "%" + term + "%");            try (ResultSet rs = ps.executeQuery()) {                System.out.println("Products containing '" + term + "':");                while (rs.next()) System.out.println("  " + rs.getString(1));            }        }    }
    public static void main(String[] args) throws SQLException {        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) {            search(con, "Power");            search(con, "Cable");        }    }}
Output
Products containing 'Power':
  Mi Power Bank 20000mAh
Products containing 'Cable':
  USB-C Cable 1m

What this code does

  • The SQL is just LIKE ?. The % wildcards are added to the bound value, "%" + term + "%", not to the SQL text.
  • Because the term is still a plain value, the search is safe even if a user types a quote or a SQL keyword.

Building LIKE '%" + term + "%' into the SQL brings back the injection you just removed.

Find the bug

Find the wrong line

Select the line that is wrong.

This search should find names containing term, but fails. Which line is wrong?

Round 1 of 3

IN lists: one ? per value

column IN (?, ?, ?) needs one ? per value, and the number of values is known only at run time. Example 5 builds that many marks and binds each value in a loop.

Example 5 · An IN list with one ? per value

Runs in: a Maven project with the MySQL driver and the ShopLite database

InList.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.Collections;import java.util.List;
public class InList {    static void namesForSkus(Connection con, List<String> skus) throws SQLException {        String marks = String.join(", ", Collections.nCopies(skus.size(), "?"));        String sql = "SELECT sku, name FROM products WHERE sku IN (" + marks + ") ORDER BY sku";        try (PreparedStatement ps = con.prepareStatement(sql)) {            for (int i = 0; i < skus.size(); i++) {                ps.setString(i + 1, skus.get(i));            }            try (ResultSet rs = ps.executeQuery()) {                while (rs.next()) System.out.println(rs.getString(1) + " -> " + rs.getString(2));            }        }    }
    public static void main(String[] args) throws SQLException {        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) {            namesForSkus(con, List.of("BK-CLEAN", "MOB-IP15", "ACC-M331"));        }    }}
Output
ACC-M331 -> Logitech M331 Silent Mouse
BK-CLEAN -> Clean Code
MOB-IP15 -> iPhone 15 128GB

What this code does

  • Collections.nCopies(3, "?") joined with commas builds ?, ?, ?, so the SQL has exactly one placeholder per SKU.
  • The loop binds parameters 1, 2 and 3. The SKU values never enter the SQL text, so the list is injection-safe at any length.

MySQL also limits the size of one statement (max_allowed_packet), so split a very long list into several queries.

Next step

Check your understanding

10 quick questions