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

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

问题描述

我的数据库中有一个类型为 double 的列,我想使用 JDBC 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. What is the best way of doing this? I can think of three options none of which seem very good.

选项 1:糟糕,因为异常处理冗长且臭

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;
   }
}

选项 2:糟糕,因为两次获取

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
}

选项 3:糟糕,因为 Java 而不是 SQL 转换

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
}

关于哪种方式更好的任何建议,或者还有另一种更好的方式?并且请不要说使用 Hibernate",我这里只限于 JDBC 代码.

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.

推荐答案

选项 1 最接近:

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

它不是很好,但那是 JDBC.如果列为空,则双精度值被认为是错误的",因此每次读取数据库中可以为空的原语时,都应该使用 wasNull() 进行检查.

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

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