JDBC Database Query
Demonstrates connecting to a database using JDBC, executing parameterized queries with PreparedStatement, and processing ResultSet with proper resource cleanup.
Code
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class JdbcDatabaseQuery {
record User(int id, String name, String email) {}
public static List<User> findActiveUsers(String url, String user, String pass) {
String sql = "SELECT id, name, email FROM users WHERE active = ? ORDER BY name";
List<User> users = new ArrayList<>();
try (Connection conn = DriverManager.getConnection(url, user, pass);
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setBoolean(1, true);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
users.add(new User(
rs.getInt("id"),
rs.getString("name"),
rs.getString("email")
));
}
}
} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
}
return users;
}
public static void main(String[] args) {
System.out.println("JDBC query example ready to connect");
}
}How it works
JDBC Database Query reduces to the classes JdbcDatabaseQuery and User and the functions findActiveUsers and main.
Repetition is confined to while (rs.next()) — the rest of the file is straight-line. Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.
Using it
Entry signature: public static List<User> findActiveUsers(String url, String user, String pass)
Look for the JDBC query example ready to connect prefixes when the file runs; they tie each line to its step.
Key statements
String sql = "SELECT id, name, email FROM users WHERE active = ? ORDER BY name";
List<User> users = new ArrayList<>();
stmt.setBoolean(1, true);
Interactive Tools for This Topic
SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.
FAQ
- What does JDBC Database Query print when run?
- Execute the whole file; each printed line is prefixed with a label like `JDBC query example ready to connect`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.