19

ResultSet#getBoolean seems to return false when it's null.
Is there an easy way to get a Boolean (not boolean) from a ResultSet?

Priv
  • 812
  • 2
  • 9
  • 23

5 Answers5

19

You can call wasNull after calling getBoolean. It's explained here: https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#wasNull%28%29

uoyilmaz
  • 3,035
  • 14
  • 25
8

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();
    }
Alexey Soshin
  • 16,718
  • 2
  • 31
  • 40
4

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.

theyuv
  • 1,556
  • 4
  • 26
  • 55
4
resultSet.getObject(1) == null ? null : resultSet.getBoolean(1)
Alex78191
  • 2,383
  • 2
  • 17
  • 24
0

You can use java optional for that:

    public static Boolean getNullableBoolean(ResultSet rs, String column) throws SQLException {
        return Optional.ofNullable((Boolean)rs.getObject(column))
                       .map(Boolean::booleanValue).orElse(null);
    }

...

getNullableBoolean(rs, "my_boolean_column")
Ricardo Mayerhofer
  • 2,121
  • 20
  • 22