ResultSet#getBoolean seems to return false when it's null.
Is there an easy way to get a Boolean
(not boolean
) from a ResultSet
?
Asked
Active
Viewed 2.1k times
5 Answers
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
-
So I'd have to use: `Boolean foo = result.getBoolean("bar"); if (result.wasNull()) foo = null;`? – Priv Sep 18 '16 at 18:27
-
Yes, you can use it like that. – uoyilmaz Sep 18 '16 at 18:27
-
Thanks, great help – leole Jul 10 '17 at 07:09
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
-
-
@NadavB, that shouldn't be the case, at least for MySQL. I added a full example. – Alexey Soshin Mar 24 '17 at 10:40
-
it happened to me with postgresql. The second answer with the wasNull worked for me fine. So maybe your answer is only for mySQL? – Nathan B Mar 25 '17 at 18:04
-
@NadavB, yes, as the original question was related to MySQL only. – Alexey Soshin Mar 26 '17 at 15:57
-
1This will also return false when the DB column is null, which is what the OP was trying to avoid. – theyuv Apr 03 '19 at 14:16
-
This solution worked very well for me, using AS400/DB2. Thanks Alexey! – jfajunior Jul 01 '19 at 12:33
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
-
-
You're casting an `Object` to `Boolean`. https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#getObject(int) – theyuv Jun 10 '19 at 15:45
-
`The type of the Java object will be the default Java object type corresponding to the column's SQL type`. Read about casting. – Alex78191 Jun 10 '19 at 15:48
-
1In Oracle there is no boolean column, but method getBoolean is working. – Alex78191 Jun 20 '19 at 16:20
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