- What technique is used to load JDBC drivers?
Since JDBC 4.0, drivers on the classpath are discovered and registered automatically via the Service Provider mechanism.
You usually do not need Class.forName(...)
. Keep it only for legacy runtimes, special classloader setups, or when explicitly required by a driver.
- What does
Class.forName(...)
do when loading drivers?
It loads the driver class and triggers its static initializer, which registers the driver with DriverManager
.
With modern drivers (JDBC 4+), this explicit step is typically unnecessary because registration happens automatically.
- How is a JDBC connection established?
Use a Type‑4 driver URL and DriverManager
(standalone) or a pooled DataSource
(server/container). Always use try‑with‑resources.
Example (standalone, PostgreSQL):
String url = "jdbc:postgresql://localhost:5432/app";
try (java.sql.Connection con =
java.sql.DriverManager.getConnection(url, "app_user", "secret")) {
// use the connection
}
- How do you create JDBC statements?
Prefer PreparedStatement
for parameters and safety; use Statement
only for static SQL; use CallableStatement
for stored procedures.
// Preferred
try (PreparedStatement ps = con.prepareStatement(
"UPDATE users SET status=? WHERE id=?")) {
ps.setString(1, "ACTIVE");
ps.setLong(2, userId);
ps.executeUpdate();
}
- How do you create and execute a query?
String sql = "SELECT data FROM my_table WHERE category = ?";
try (PreparedStatement ps = con.prepareStatement(sql)) {
ps.setString(1, "REPORT");
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
String data = rs.getString("data");
// process row
}
}
}
The results are returned as a ResultSet
that you iterate with while (rs.next())
.
- How can you retrieve data from a
ResultSet
?
Use typed getters by column label or index. Prefer labels for readability and indexes for speed (when stable).
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
String name = rs.getString("COF_NAME");
java.math.BigDecimal price = rs.getBigDecimal("PRICE");
}
}
- How do you navigate a
ResultSet
?
By default, a ResultSet
is TYPE_FORWARD_ONLY. Random access methods require a scrollable result set:
try (Statement st = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY)) {
try (ResultSet rs = st.executeQuery("SELECT * FROM items")) {
rs.first(); // first row
rs.last(); // last row
rs.beforeFirst(); // position before first row
rs.afterLast(); // position after last row
rs.absolute(5); // go to row 5 (1-based)
rs.relative(-2); // move back two rows
rs.previous(); // move back one row
}
}
Note: last()
moves to the last row (not “before the last”). Support may vary by driver for TYPE_SCROLL_SENSITIVE.
- What are the different JDBC statement types?
- Statement — Ad‑hoc SQL without parameters (rarely recommended).
- PreparedStatement — Parameterized SQL; safer and often faster; supports batching; preferred for most operations.
- CallableStatement — Calls stored procedures with IN/OUT parameters.
- How do you search for a literal
%
without it acting as a wildcard?
Use a parameterized query and (optionally) an SQL ESCAPE
clause. The exact escape character support is database‑specific.
String sql = "SELECT tax FROM sales WHERE tax LIKE ? ESCAPE '\\\\'";
try (PreparedStatement ps = con.prepareStatement(sql)) {
ps.setString(1, "10\\\\%"); // matches literal "10%"
try (ResultSet rs = ps.executeQuery()) { /* ... */ }
}
Avoid manual string concatenation; let the driver handle quoting and escaping.
- How do you handle single quotes in input safely?
Use PreparedStatement parameters. The driver quotes values correctly and prevents SQL injection:
String sql = "INSERT INTO notes(message) VALUES (?)";
try (PreparedStatement ps = con.prepareStatement(sql)) {
ps.setString(1, userInput); // handles embedded ' characters safely
ps.executeUpdate();
}
Only if you absolutely must build SQL strings manually, escape '
as ''
(two quotes), but this is discouraged compared to parameterized queries.