针对“空基元"的变通方法是:在JDBC PreparedStatement中? [英] Workaround for "null primitives" in 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);
...
在这里,如果someString
是null
,那很好-字符串可以为空.但是,如果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屋!