[英]How do I in JDBC read a possibly null double value from resultSet?
I have a column in my database that is typed double
and I want to read the value from it using a JDBC ResultSet, but it may be null. 我的数据库中有一个类型为
double
的列,我想使用JDBC ResultSet从中读取值,但它可能为null。 What is the best way of doing this? 这样做的最佳方式是什么? I can think of three options none of which seem very good.
我可以想到三个选项,其中没有一个看起来非常好。
Option 1: Bad because exception handling verbose and smelly 选项1:错误,因为异常处理冗长和臭
double d;
try {
d = rs.getDouble(1);
// do something
} catch(SQLException ex) {
if(rs.wasNull()) {
// do something else
} else {
throw ex;
}
}
Option 2: Bad because two fetches 选项2:因为两个提取而不好
s = rs.getString(1); // or getObject()
if(s == null) {
// do something else
} else {
double d = rs.getDouble(1);
// do something
}
Option 3: Bad because Java rather than SQL conversion 选项3:错误因为Java而不是SQL转换
s = rs.getString(1); // or getObject()
if(s == null) {
// do something else
} else {
double d = Double.parseDouble(s);
// do something
}
Any suggestions on which way is better, or is there another superior way? 有关哪条路更好的建议,还是有其他优越方式? And please don't say "Use Hibernate", I'm restricted to JDBC code only here.
请不要说“使用Hibernate”,我只限于这里的JDBC代码。
Option 1 is closest: 选项1最接近:
double d = rs.getDouble(1);
if (rs.wasNull()) {
// do something
} else {
// use d
}
It's not very nice, but that's JDBC. 它不是很好,但那是JDBC。 If the column was null, the double value is considered "bad", so you should check using
wasNull()
every time you read a primitive that is nullable in the database. 如果列为null,则double值被视为“bad”,因此每次读取数据库中可为空的基元时都应使用
wasNull()
检查。
Depending on your JDBC driver and database, you may be able to use a boxed type and cast: 根据您的JDBC驱动程序和数据库,您可以使用盒装类型和强制转换:
Double doubleValueOrNull = (Double)rs.getObject(1); // or .getObject("columnName")
It will be null
if the column was NULL
. 这将是
null
,如果柱NULL
。
Be careful to check this still works if you change database. 如果更改数据库,请小心检查这是否仍然有效。
使用:
rs.getObject(1)==null?null:rs.getBigDecimal(1).doubleValue()
Or with java 8 you can do this: 或者使用java 8,您可以这样做:
Double dVal = Optional.ofNullable(resultSet.getBigDecimal("col_name"))
.map(BigDecimal::doubleValue).orElse(null));
用于检索可空字段的Kotlin版本:
val parentId = resultSet.getObject("parent_id") as Double?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.