Getting Boolean from ResultSet
16,292
Solution 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
Solution 2
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();
}
Solution 3
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.
Solution 4
resultSet.getObject(1) == null ? null : resultSet.getBoolean(1)
Author by
Priv
Updated on June 01, 2022Comments
-
Priv almost 2 years
ResultSet#getBoolean seems to return false when it's null.
Is there an easy way to get aBoolean
(notboolean
) from aResultSet
? -
Priv over 7 yearsSo I'd have to use:
Boolean foo = result.getBoolean("bar"); if (result.wasNull()) foo = null;
? -
uoyilmaz over 7 yearsYes, you can use it like that.
-
Nathan B about 7 yearsIt throws java.lang.AbstractMethodError
-
Alexey Soshin about 7 years@NadavB, that shouldn't be the case, at least for MySQL. I added a full example.
-
Nathan B about 7 yearsit happened to me with postgresql. The second answer with the wasNull worked for me fine. So maybe your answer is only for mySQL?
-
Alexey Soshin about 7 years@NadavB, yes, as the original question was related to MySQL only.
-
leole almost 7 yearsThanks, great help
-
theyuv about 5 yearsThis will also return false when the DB column is null, which is what the OP was trying to avoid.
-
Alex78191 almost 5 years
Integer
cannot be casted toBoolean
. -
theyuv almost 5 years
-
Alex78191 almost 5 years
The type of the Java object will be the default Java object type corresponding to the column's SQL type
. Read about casting. -
Alex78191 almost 5 yearsIn Oracle there is no boolean column, but method getBoolean is working.
-
jfajunior almost 5 yearsThis solution worked very well for me, using AS400/DB2. Thanks Alexey!