Congratulations, you've hit my favorite pet peeve with JDBC: Date class handling.
Basically databases usually support at least three forms of datetime fields which are date, time and timestamp. Each of these have a corresponding class in JDBC and each of them extend
Do note that if you use
Basically databases usually support at least three forms of datetime fields which are date, time and timestamp. Each of these have a corresponding class in JDBC and each of them extend
java.util.Date
. Quick semantics of each of these three are the following:java.sql.Date
corresponds to SQL DATE which means it stores years, months and days while hour, minute, second and millisecond are ignored. Additionallysql.Date
isn't tied to timezones.java.sql.Time
corresponds to SQL TIME and as should be obvious, only contains information about hour, minutes, seconds and milliseconds.java.sql.Timestamp
corresponds to SQL TIMESTAMP which is exact date to the nanosecond (note thatutil.Date
only supports milliseconds!) with customizable precision.
sql.Date
is timezone specific, sql.Time
contains current year, month and day et cetera et cetera.Finally: Which one to use?
Depends on the SQL type of the field, really.PreparedStatement
has setters for all three values, #setDate()
being the one for sql.Date
, #setTime()
for sql.Time
and #setTimestamp()
for sql.Timestamp
.Do note that if you use
ps.setObject(fieldIndex, utilDateObject);
you can actually give a normal util.Date
to most JDBC drivers which will happily devour it as if it was of the
correct type but when you request the data afterwards, you may notice
that you're actually missing stuff.
java程序学习编程
ReplyDelete在java编码中继续语句
Thanks for the blog. It was great to read.
ReplyDeleteJava classes in Pune