Workaround for “null primitives” in JDBC PreparedStatement? [duplicate]

假装没事ソ 提交于 2020-01-20 05:56:45

问题


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);

...

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

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

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

So what's the workaround?


回答1:


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




回答2:


You can use the setNull(int parameterIndex, int sqlType) method of the PreparedStatement class.

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.




回答3:


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



来源:https://stackoverflow.com/questions/17657057/workaround-for-null-primitives-in-jdbc-preparedstatement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!