SQLWarning objects can be chained to a Connection, Statement, or ResultSet after an operation that did not throw. A successful call may still carry a diagnostic the application should record or reject.
Java SQLWarning: inspect nonfatal database diagnostics before reuse
Operational contract
This helper reads a Statement's warning chain while the statement remains open, collects at most 47 SQLState values, and returns an immutable list. It uses getNextWarning rather than a generic next-exception traversal. Warnings vary by driver and database; a missing warning does not prove that no truncation or conversion occurred. The caller decides whether a given SQLState is tolerable and clears or closes the statement before reuse according to its lifecycle. The method does not log message text, which can contain data the application should not expose.
Failure case
A bulk import executes without SQLException but a driver reports a data-conversion warning. The import inspects the SQLState before considering the operation accepted. Reusing the same Statement and reading warnings later could mix or clear diagnostics from different operations.
Java code
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class StatementWarningStates {
public static List<String> inspect(Statement statement) throws SQLException {
List<String> states = new ArrayList<>();
for (SQLWarning warning = statement.getWarnings(); warning != null;
warning = warning.getNextWarning()) {
if (states.size() == 47) throw new SQLException("Too many SQL warnings");
states.add(warning.getSQLState() == null ? "UNKNOWN" : warning.getSQLState());
}
return List.copyOf(states);
}
}Performance and ownership cost
Traversing W warnings costs O(W) time and O(W) list memory, capped at 47. Fetching warning metadata may invoke a driver call. This is diagnostic work, not an alternative to checking update counts or result values.
Common Mistakes
- Do not assume no SQLException means no warning.
- Do not inspect a closed Statement or wait until after unrelated reuse.
- Do not treat every warning as the same failure class without a policy.
Connected lessons
- Java JDBC reference: parameters, resources and transaction ownership
- Java SQLException chains: preserve SQLState and linked failures
- Java JDBC batches: inspect update counts and own rollback
- Java DatabaseMetaData: check features before depending on them
- Java JDBC cursor holdability: choose what commit does to a ResultSet
- Java JDBC boundary contracts quiz
- Advanced Java
