java JDBC PreparedStatement 中“空原语”的解决方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17657057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Workaround for "null primitives" in JDBC PreparedStatement?
提问by IAmYourFaja
When using raw JDBC, you can parameterize a PreparedStatementlike so:
使用原始 JDBC 时,您可以PreparedStatement像这样参数化:
PreparedStatement statement = connection.prepareStatement(someSQLString);
String someString = getSomeString();
Integer int = getSomeInteger();
statement.setString(1, someString);
statement.setLong(2, 5L);
statement.setInt(3, int);
...
Here, if someStringis null, that's fine - strings are nullable. But if getSomeInteger()returns null, we have a problem.
在这里,如果someString是null,那很好 - 字符串可以为空。但是如果getSomeInteger()返回null,我们就有问题了。
PreparedStatement#setInt(int,int)sets a primitive intas the value, and therefore cannot be null.
PreparedStatement#setInt(int,int)将原始int值设置为值,因此不能为null。
However, it's perfectly plausible that I might want the value of the 3rd column above to be nullfor this particular record.After all, every RDBMS I've ever worked with allows numeric (INT, LONG, etc.) fields to be NULLABLE...
但是,我可能希望上面第 3 列的值null用于此特定记录是完全合理的。毕竟,我曾经使用过的每个 RDBMS 都允许数字(INT、LONG 等)字段为 NULLABLE...
So what's the workaround?
那么有什么解决方法呢?
回答by Luiggi Mendoza
回答by Konstantin Yovkov
You can use the setNull(int parameterIndex, int sqlType)method of the PreparedStatementclass.
您可以使用该类的setNull(int parameterIndex, int sqlType)方法PreparedStatement。
Here's an example of how to use it:
以下是如何使用它的示例:
String query =
"insert into nullable_table(id,string_column, int_column) values(?, ?, ?)";
// create PrepareStatement object
PreparedStatement pstmt = connection.prepareStatement(query);
pstmt.setString(1, id);
pstmt.setNull(2, java.sql.Types.VARCHAR);
pstmt.setNull(3, java.sql.Types.INTEGER);
Example taken from here.
示例取自此处。

