Java 如何从结果集中得到一个 Double 而不是 double?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2158187/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:13:01  来源:igfitidea点击:

How do I get a Double out of a resultset instead of double?

javajdbc

提问by benstpierre

When working with a JDBC resultset I want to get Double instead of double since this column is nullable. Rs.getDouble returns 0.0 when the column is null.

使用 JDBC 结果集时,我想得到 Double 而不是 double,因为该列可以为空。当列为空时,Rs.getDouble 返回 0.0。

采纳答案by Peter Lang

You can check for wasNullon your ResultSet to find out if the value was null.

您可以检查wasNullResultSet 以了解该值是否为null.

Note that you must first call one of the getter methods on a column to try to read its value and then call the method wasNull to see if the value read was SQL NULL.

请注意,您必须首先调用列上的 getter 方法之一以尝试读取其值,然后调用方法 wasNull 以查看读取的值是否为 SQL NULL。

If you really need a Doubleafterwards, you can create it from the doublereturned.

如果您真的需要Double事后,您可以从double返回的内容中创建它。

回答by Yoni

Use ResultSet.wasNull -> http://java.sun.com/javase/6/docs/api/java/sql/ResultSet.html#wasNull%28%29

使用 ResultSet.wasNull -> http://java.sun.com/javase/6/docs/api/java/sql/ResultSet.html#wasNull%28%29

Basically it works for all primitive types, you first use getDouble, getInt, etc., and then only if the result is 0 you use wasNull.

基本上,它适用于所有基本类型,你第一次使用getDoublegetInt等等,然后仅当结果是你用0 wasNull

回答by BalusC

An alternative to the aforementioned ResultSet#wasNull()is to test ResultSet#getObject()on nullso that you can nicely put it in a single line in combination with the ternary operator:

上述的替代方法ResultSet#wasNull()是进行测试ResultSet#getObject()null以便您可以很好地将它与三元运算符组合在一起放在一行中:

Double d = resultSet.getObject("column") != null ? resultSet.getDouble("column") : null;

instead of

代替

Double d = resultSet.getDouble("column");
if (resultSet.wasNull()) {
    d = null;
}

回答by MRhodes

You could just do:

你可以这样做:

Double d = (Double) resultSet.getObject("column");

Double d = (Double) resultSet.getObject("column");

then you don't have to worry if it was null.

那么你不必担心它是否为空。