ResultSet#getBoolean seems to return false when it's null.
Is there an easy way to get a Boolean
(not boolean
) from a ResultSet
?
Getting Boolean from ResultSet
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
Yes, you can use it like that. –
Marceau
Thanks, great help –
Timothea
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();
}
It throws java.lang.AbstractMethodError –
Exothermic
@NadavB, that shouldn't be the case, at least for MySQL. I added a full example. –
Cholecyst
it happened to me with postgresql. The second answer with the wasNull worked for me fine. So maybe your answer is only for mySQL? –
Exothermic
@NadavB, yes, as the original question was related to MySQL only. –
Cholecyst
This will also return false when the DB column is null, which is what the OP was trying to avoid. –
Ligate
This solution worked very well for me, using AS400/DB2. Thanks Alexey! –
Humoresque
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.
Integer
cannot be casted to Boolean
. –
Timmy You're casting an
Object
to Boolean
. docs.oracle.com/javase/7/docs/api/java/sql/… –
Ligate The type of the Java object will be the default Java object type corresponding to the column's SQL type
. Read about casting. –
Timmy In Oracle there is no boolean column, but method getBoolean is working. –
Timmy
resultSet.getObject(1) == null ? null : resultSet.getBoolean(1)
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")
This is redundant -- you are converting a Boolean to a boolean with "booleanValue()", then converting it back again by returning it to a boxed Boolean context. Your code is entirely equivalent to doing
return (Boolean)rs.getObject(column)
. HTH! –
Redraft © 2022 - 2024 — McMap. All rights reserved.
Boolean foo = result.getBoolean("bar"); if (result.wasNull()) foo = null;
? – Ryeland