java
40 lines · 7 steps
Safe parameterized JDBC queries in Java
A JDBC query that filters users by email domain, guarding against both SQL injection and LIKE-pattern injection.
Explained by
highlit
1public List<User> findUsersByEmailDomain(String domain, int minAge) {
2 String sql = """
3 SELECT id, username, email, age, created_at
4 FROM users
5 WHERE email LIKE ?
6 AND age >= ?
7 AND active = TRUE
8 ORDER BY created_at DESC
9 LIMIT ?
10 """;
11
12 List<User> results = new ArrayList<>();
13
14 try (Connection conn = dataSource.getConnection();
15 PreparedStatement stmt = conn.prepareStatement(sql)) {
16
17 String escaped = domain.replace("!", "!!")
18 .replace("%", "!%")
19 .replace("_", "!_");
20 stmt.setString(1, "%@" + escaped);
21 stmt.setInt(2, minAge);
22 stmt.setInt(3, MAX_RESULTS);
23
24 try (ResultSet rs = stmt.executeQuery()) {
25 while (rs.next()) {
26 User user = new User();
27 user.setId(rs.getLong("id"));
28 user.setUsername(rs.getString("username"));
29 user.setEmail(rs.getString("email"));
30 user.setAge(rs.getInt("age"));
31 user.setCreatedAt(rs.getTimestamp("created_at").toInstant());
32 results.add(user);
33 }
34 }
35 } catch (SQLException e) {
36 throw new DataAccessException("Failed to query users by domain: " + domain, e);
37 }
38
39 return results;
40}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Prepared statements with placeholders keep user input out of the SQL text, closing the injection door.
- 2LIKE patterns need a second escaping pass because % and _ are wildcards even inside a parameter.
- 3Try-with-resources on connections, statements, and result sets guarantees cleanup even when queries throw.
Related explainers
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
java
public final class EncodingDetector { public enum Encoding { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN
Detecting text encoding from raw bytes in Java
byte-manipulation
encoding-detection
bitwise-operations
Intermediate
8 steps
java
public final class ImportOrganizer { private static final Pattern IMPORT_LINE = Pattern.compile("^import\\s+(static\\s+)?([\\w.]+(?:\\.\\*)?)\\s*;\\s*$");
Sorting Java imports with a regex pass
regex
sorting
text-processing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/safe-parameterized-jdbc-queries-in-java-explained-java-c8ad/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.