Storing NULL values in DB

applekanna
applekanna used Ask the Experts™
on
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!
                                                               
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
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();

Author

Commented:
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
Commented:
You don't have to convert java.sql.Date to java.util.Date.

java.sql.Date is a java.util.Date (it's a subclass of the latter).

Not sure what other problem you have.
Exploring SQL Server 2016: Fundamentals

Learn the fundamentals of Microsoft SQL Server, a relational database management system that stores and retrieves data when requested by other software applications.

Author

Commented:
oops..
I tried this when it gave me an error
PreparedStatement pstmt
 
pstmt.setDate(utildate);

Author

Commented:
I should have type casted it.

pstmt.setDate(11, (java.sql.Date)utilDate);

Commented:
You need to convert java.util.Date to java.sql.Date as follows:

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

Author

Commented:
Thank you

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial