Reputation: 75
I have a database with more than 20 columns and some of them are date
/timestamp
data types with null values.
Java application will read the data from this table and insert into other table. Prepared Statement is used to frame insert query. When inserting the record, I get "null pointer exception" on date columns where ever it is null. For the Varchar
, it is automatically setting to null when the actual value is null. Is there any way to handle the Date fields with null values automatically as like varchar
in prepared statements?
PreparedStatement ps = null;
....
....
ps.setDate(3, new java.sql.Date(date.getTime())); //date is Java.Util.Date
Getting Error. So I handle manually like below
if(date!= null)
ps.setDate(3, new java.sql.Date(date.getTime()));
else
ps.setNull(3, Types.DATE);
Upvotes: 0
Views: 3367
Reputation: 1074276
The problem, of course, is that you're trying to call getTime
on date
, which may be null
.
Java application will read the data from this table and insert into other table.
If that's true, then I'd expect date
to already be a java.sql.Date
(or null
) and you could just use it directly:
ps.setDate(3, date);
If date
is really not a java.sql.Date
, then you can use the conditional operator:
ps.setDate(3, date == null ? null : new java.sql.Date(date.getTime()));
It's fine to pass null
into setDate
(for the same reason it works in setString
). You only need setNull
when the Java type you'd use with the column is a primitive type (like int
). Since you can't call setInt
with null
where the int
should be, you'd use setNull
in that situation. That's not an issue for setDate
, though.
Upvotes: 1