ResultSet#getBoolean seems to return false when it's null.
Is there an easy way to get a Boolean
(not boolean
) from a ResultSet
?
The wasNull() method of the ResultSet interface determines whether the last column read had a Null value. i.e. whenever you read the contents of a column of the ResultSet using the getter methods (getInt(), getString etc...) you can determine whether it (column) contains null values, using the wasNull() method.
getString(String columnLabel) Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language. Time. getTime(int columnIndex) Retrieves the value of the designated column in the current row of this ResultSet object as a java.
This method returns a boolean value specifying whether the ResultSet object contains more rows. If there are no rows next to its current position this method returns false, else it returns true.
The ResultSet interface declares getter methods (for example, getBoolean and getLong ) for retrieving column values from the current row. You can retrieve values using either the index number of the column or the alias or name of the column. The column index is usually more efficient. Columns are numbered from 1.
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
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();
}
resultSet.getObject(1) == null ? null : resultSet.getBoolean(1)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With