Getting Boolean from ResultSet Getting Boolean from ResultSet mysql mysql

Getting Boolean from ResultSet


This should work:

    try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test?serverTimezone=UTC");){        // create table bool_table (bool_value boolean);        // insert into bool_table values (null);        String sql = "SELECT * FROM bool_table";        try (PreparedStatement preStmt = conn.prepareStatement(sql)){            try (ResultSet rs = preStmt.executeQuery()) {                rs.next();                System.out.println(rs.getObject(1, Boolean.class));            }        } catch (SQLException e) {            e.printStackTrace();        }    } catch (SQLException ex) {        ex.printStackTrace();    }


You should get the desired result (ie: null when the column value is null) by using ResultSet.getObject() and then casting to a Boolean Object.

Like this:

Boolean someBool = (Boolean) rs.getObject("booleanColumnName");

I think this is safe as long as your column type corresponds to boolean (ie: TINYINT(1)), But test it.

This answer does the same thing but with the Integer Object.