SQLException
JavaERRORNotableDatabase

Database access error

Quick Answer

Log getSQLState() and getErrorCode() alongside getMessage() to identify the specific database error.

What this means

Base class for all JDBC database errors — carries a SQLState code, vendor error code, and message.

Why it happens
  1. 1SQL syntax error in the query string
  2. 2Constraint violation (unique, foreign key, not null)

Fix

Log SQLState and vendor code

Log SQLState and vendor code
try {
    stmt.executeUpdate(sql);
} catch (SQLException e) {
    log.error("SQLState={} code={} msg={}",
        e.getSQLState(), e.getErrorCode(), e.getMessage());
}

Why this works

SQLState is standardised; vendor codes give DB-specific detail.

Code examples
Try-with-resources connectionjava
try (Connection c = ds.getConnection();
     PreparedStatement ps = c.prepareStatement(sql)) {
    ps.setInt(1, id);
    ResultSet rs = ps.executeQuery();
}
Distinguish constraint violationsjava
catch (SQLException e) {
    if ("23000".equals(e.getSQLState())) {
        // unique or FK constraint violation
    }
}
Use named parameters (Spring)java
namedJdbc.update(
    "INSERT INTO users(name) VALUES (:name)",
    Map.of("name", username));
Sources
Official documentation ↗

Java SE Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Java errors