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

发布于 2024-08-31 23:50:05 字数 442 浏览 1 评论 0原文

当使用 JDBC 并通过结果集访问基本类型时,有没有比以下更优雅的方法来处理 null/0:

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

每当我看到这种代码时,我个人都会感到畏缩。我不明白为什么 ResultSet 没有定义为返回装箱整数类型(也许性能除外)或至少提供两者。如果有人能让我相信当前的 API 设计很棒,那就加分了:)

我个人的解决方案是编写一个返回 Integer 的包装器(我更关心客户端代码的优雅而不是性能),但我想知道我是否缺少更好的方法来做到这一点。

需要澄清的是,这段代码让我困扰的不是长度,而是它在后续调用之间创建了状态依赖关系,而看似简单的 getter 实际上在同一行中具有副作用。

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:

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. Bonus points if anyone can convince me that the current API design is great :)

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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

逆夏时光 2024-09-07 23:50:05

JDBC API 是为了性能而设计的。请记住,它可以追溯到 Java 1.1,当时对象的大量周转是 JVM 杀手(直到 Java 1.2+ 中的 Hotspot JVM 才可以放松这种限制)。使用盒装类型会破坏当时大容量应用程序的性能。

现在,由于向后兼容性,它无法更改。所以不,它不再理想了,但它是一个非常小的解决方法。

如果您想避免您提到的代码类型,则始终可以使用 getObject() 而不是 getInt(),它将返回以下子类型之一的对象java.lang.Number,可能是 IntegerBigInteger,具体取决于具体的 SQL 类型。

The JDBC API was designed for performance. 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). 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文