Link to home
Start Free TrialLog in
Avatar of applekanna
applekanna

asked on

Storing NULL values in DB

Hi
I have a date field that might or might not contain data. What do you suggest I store it as
I store it as NULL riht now, but it is causing some problems such as nullPointer Exceptions.

My questions is -> what do experts do?
                      1. store null and then do a try catch whenever we access it
                  or 2. use a dummy date as 1901-01-01 as date and then change it during display as "" <empty string>

Thank you!
                                                               
Avatar of yongsing
yongsing

Use option 1.

When you access it, you test it for null:

ResultSet resultSet = statement.executeQuery("select datecol from yourtable");
while (resultSet.next()) {
    Date date = resultSet.getDate(1);

    // test to see if date is null
    if (date != null) {
        // do something with the date
    }

}
resultSet.close();
Avatar of applekanna

ASKER

I got this problem becoz it was like this

ResultSet resultSet = statement.executeQuery("select datecol from yourtable");

    java.util.Date date = resultSet.getDate(1);//this returns java.sql.Data

resultSet.close();

I added a private method to later conver sql date to util date and added a try catch there.
Looking for your expert opinion
ASKER CERTIFIED SOLUTION
Avatar of yongsing
yongsing

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
oops..
I tried this when it gave me an error
PreparedStatement pstmt
 
pstmt.setDate(utildate);
I should have type casted it.

pstmt.setDate(11, (java.sql.Date)utilDate);
You need to convert java.util.Date to java.sql.Date as follows:

pstmt.setDate(11, new java.sql.Date(utilDate.getTime()));
Thank you