针对“空基元"的变通方法是:在JDBC PreparedStatement中? [英] Workaround for "null primitives" in JDBC PreparedStatement?

查看:126
本文介绍了针对“空基元"的变通方法是:在JDBC PreparedStatement中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用原始JDBC时,您可以像这样对PreparedStatement进行参数设置:

When using raw JDBC, you can parameterize a PreparedStatement like so:

PreparedStatement statement = connection.prepareStatement(someSQLString);
String someString = getSomeString();
Integer int = getSomeInteger();
statement.setString(1, someString);
statement.setLong(2, 5L);
statement.setInt(3, int);

...

在这里,如果someStringnull,那很好-字符串可以为空.但是,如果getSomeInteger()返回null,我们就会遇到问题.

Here, if someString is null, that's fine - strings are nullable. But if getSomeInteger() returns null, we have a problem.

PreparedStatement#setInt(int,int)设置原始int作为值,因此不能为null.

PreparedStatement#setInt(int,int) sets a primitive int as the value, and therefore cannot be null.

但是,对于上述特定记录,我可能希望上面第三列的值为null是完全合理的.毕竟,我曾经使用过的每个RDBMS都允许数字( INT,LONG等)字段为NULLABLE ...

However, it's perfectly plausible that I might want the value of the 3rd column above to be null for this particular record. After all, every RDBMS I've ever worked with allows numeric (INT, LONG, etc.) fields to be NULLABLE...

那是什么解决方法?

推荐答案

请勿使用其中任何一项,而应使用

Don't use any of those and use setObject instead, let the JDBC driver to manage the null values instead of you.

这篇关于针对“空基元"的变通方法是:在JDBC PreparedStatement中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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