我如何在JDBC中从resultSet读取可能为空的double值? [英] How do I in JDBC read a possibly null double value from resultSet?

查看:315
本文介绍了我如何在JDBC中从resultSet读取可能为空的double值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库中有一列,键入 double ,我想使用JDBC ResultSet读取它的值,但可能为null。这样做最好的方法是什么?我可以想到三个选项,其中没有一个似乎非常好。



选项1:因为异常处理冗长和臭味

  double d; 
try {
d = rs.getDouble(1);
//做某事
} catch(SQLException ex){
if(rs.wasNull()){
// do something else
} else {
throw ex;
}
}

选项2:由于两次提取

  s = rs.getString(1); //或getObject()
if(s == null){
// do something else
} else {
double d = rs.getDouble(1);
//做某事
}

选项3:错误,因为Java而不是SQL转换

  s = rs.getString(1); //或getObject()
if(s == null){
// do something else
} else {
double d = Double.parseDouble(s);
//做某事
}

任何建议,哪种方式更好,还是有另一个优越的方式?请不要说使用Hibernate,我仅限于JDBC代码。

解决方案

选项1最接近:

  double d = rs.getDouble(1); 
if(rs.wasNull()){
// do something
} else {
// use d
}

这不是很好,但这是JDBC。如果列为空,则双重值被认为是坏,所以每次读取数据库中为空的原语时,应该使用 wasNull() / p>

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.

Option 1: Bad because exception handling verbose and smelly

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

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

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.

解决方案

Option 1 is closest:

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中从resultSet读取可能为空的double值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆