Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workaround for "null primitives" in JDBC PreparedStatement? [duplicate]

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?

like image 611
IAmYourFaja Avatar asked Jul 15 '13 14:07

IAmYourFaja


1 Answers

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

like image 92
Luiggi Mendoza Avatar answered Oct 17 '22 10:10

Luiggi Mendoza