4

I am working with JDBC and MySQL. I have a date column that I need included in my result set. Unfortunately, I cannot find a class in Java to retrieve the date. The SQL Date class is deprecated. How do you get Date objects from a result set?

4 Answers 4

23

You use java.sql.Date. A constructor and some methods are deprecated. The class isn't. Confused by this versus, say, java.util.Date or java.util.Calendar? Look at Making Sense of Java's Dates.

There are three JDBC date/time types:

The confusion probably arises from the fact that java.sql.Date extends java.util.Date and thus inherits its deprecated methods.

Just use the right type for the type of your column.

Sign up to request clarification or add additional context in comments.

3 Comments

The problem is that the only constructor that remains is the one to create a date passing in millis. Also, all of its set and get methods that don't use millis are deprecated. Unless SQL returns the date in millis this seems kind of silly.
Read the javadoc more closely, java.sql.Date conforms to the DATE JDBC type and the fields smaller than day are set to zero. The type is for use when you have a field that is day/month/year only and not, say, TIMESTAMP or TIME. What are you trying to do exactly?
and don't forget that java.sql.Date is a subclass of java.util.Date (some more methods)
4

I don't think the java.sql.Date class itself it deprecated, only one of its constructors. You should be safe to continue using it.

Comments

2

You can safely use the java.sql.Date class to map your MySQL DATE type. The java.sql.Date class extends the java.util.Date class, so you can use this object to do all types of date calculations.

Comments

2

Old post, but anyways:

I had problems with the granularity of java.util.Date and switched to java.util.Timestamp. I also experienced limited granularity with Timestamp type (up to seconds).

The columns in the database are declared as Date and to get the additional time part, I retrieved it as Timestamp. Problem is it truncates the value to seconds.

I investigated the Oracle default definition for timestamp which allows for 6 fractional digits.

I guess the Date part in the oracle definition limits the timestamp part in Java...

Cheers, Grazina

1 Comment

That is exactly as per the JDBC contract. If you want to store a date (day, month, year), use java.sql.Date. If you want to store a time (hour, minute, second), use java.sql.Time. If you want to store a timestamp (day, month, year, hour, minute, second, also known as datetime), use java.sql.Timestamp. Depending on the DB and JDBC driver used you also have milliseconds in the Timestamp.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.