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
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:
- DATE: granularity of days, use java.sql.Date;
- TIMESTAMP: date and time, use java.sql.Timestamp;
- TIME, just the time with no date, use java.sql.Time.
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.
3 Comments
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
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.