简体   繁体   English

在JDBC中访问ResultSet时,是否有一种优雅的方法来区分空值和实际零值?

[英]When accessing ResultSets in JDBC, is there an elegant way to distinguish between nulls and actual zero values?

When using JDBC and accessing primitive types via a result set, is there a more elegant way to deal with the null/0 than the following: 当使用JDBC并通过结果集访问基本类型时,是否有一种更优雅的方式来处理null / 0而不是以下:

int myInt = rs.getInt(columnNumber)
if(rs.wasNull())?
{
 // Treat as null
} else
{
 // Treat as 0
}

I personally cringe whenever I see this sort of code. 每当我看到这种代码时,我个人都会畏缩。 I fail to see why ResultSet was not defined to return the boxed integer types (except, perhaps, performance) or at least provide both. 我没有看到为什么没有定义ResultSet来返回盒装的整数类型(可能除了性能)或者至少提供两者。 Bonus points if anyone can convince me that the current API design is great :) 如果有人能说服我当前的API设计很棒,那么奖励积分:)

My personal solution was to write a wrapper that returns an Integer (I care more about elegance of client code than performance), but I'm wondering if I'm missing a better way to do this. 我的个人解决方案是编写一个返回Integer的包装器(我更关心客户端代码的优雅而不是性能),但我想知道我是否错过了更好的方法来执行此操作。

Just to clarify, what bothers me about this code is not the length, but the fact that a it creates a state dependency between subsequent calls, and what appears like a simple getter actually has a side effect within the same row. 只是为了澄清一下,对于这段代码困扰我的不是长度,而是它在后续调用之间创建状态依赖关系的事实,以及看似简单的getter实际上在同一行中有副作用的事实。

The JDBC API was designed for performance. JDBC API是为性能而设计的。 Remember that it dates back to Java 1.1, when a large turnover of objects was a JVM killer (it wasn't until the Hotspot JVMs in Java 1.2+ that you could relax this kind of limitation). 请记住,它可以追溯到Java 1.1,当对象的大量转换是JVM杀手时(直到Java 1.2+中的Hotspot JVM才能放松这种限制)。 Using boxed types would have ruined the performance of high volume applications at the time. 使用盒装类型会破坏当时大批量应用程序的性能。

Now, it can't be changed because of backwards compatibility. 现在,由于向后兼容性,它无法更改。 So no, it's not ideal any more, but it's a pretty minor thing to workaround. 所以不,它不再理想,但解决方法是一个非常小的事情。

If you want to avoid the type of code you mentioned, you can always use getObject() instead of getInt() , which will return an object of one of the subtypes of java.lang.Number , probably Integer or BigInteger , depending on the specific SQL type. 如果你想避免你提到的代码类型,你总是可以使用getObject()而不是getInt() ,它将返回java.lang.Number的一个子类型的对象,可能是IntegerBigInteger ,具体取决于特定的SQL类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM