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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 14:34:54  来源:igfitidea点击:

Workaround for "null primitives" in JDBC PreparedStatement?

javasqljdbcprepared-statementnullable

提问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.

在这里,如果someStringnull,那很好 - 字符串可以为空。但是如果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

Don't use any of those and use setObjectinstead, let the JDBC driver to manage the nullvalues instead of you.

不要使用其中任何一个,setObject而是使用,让 JDBC 驱动程序null代替您管理这些值。

回答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.

示例取自此处

回答by kosa

You need to use setNull()method. Based on parameter is nullor not check you need to either call setNull()(or) setInt().

您需要使用setNull()方法。根据参数 isnull或 not 检查您需要调用setNull()(or) setInt()