Java 我如何在 JDBC 中从 resultSet 读取可能为空的双精度值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1103460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I in JDBC read a possibly null double value from resultSet?
提问by Nick Fortescue
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. What is the best way of doing this? I can think of three options none of which seem very good.
我的数据库中有一个已键入的列,我double
想使用 JDBC ResultSet 从中读取值,但它可能为空。这样做的最佳方法是什么?我能想到三个选项,没有一个看起来很好。
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 代码。
采纳答案by skaffman
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. 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.
这不是很好,但那是 JDBC。如果该列为空,则双精度值被认为是“坏的”,因此wasNull()
每次读取数据库中可为空的原语时都应检查 using 。
回答by artbristol
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.
如果您更改数据库,请小心检查这是否仍然有效。
回答by Nemo
Use:
用:
rs.getObject(1)==null?null:rs.getBigDecimal(1).doubleValue()
回答by George
Or with java 8 you can do this:
或者使用 java 8 你可以这样做:
Double dVal = Optional.ofNullable(resultSet.getBigDecimal("col_name"))
.map(BigDecimal::doubleValue).orElse(null));
回答by vovahost
Kotlin version to retrieve a nullable field:
用于检索可为空字段的 Kotlin 版本:
val parentId = resultSet.getObject("parent_id") as Double?