简体   繁体   中英

Proper way to handle null value for Oracle Date datatype in prepared statement

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM