JDBC 和 MySQL,如何将 java.util.Date 持久保存到 DATETIME 列?
我正在努力了解如何让它发挥作用。我有一个准备好的语句,我想保留一个 java.util.date。这不起作用。 我尝试将其转换为 java.sql.Date,但仍然不起作用。 java日期框架有什么问题,它确实不简单。
I'm struggling to understand how to get it to work. I have a prepared statment, and I want to persist a java.util.date. It doesn't work.
I tried to cast it to java.sql.Date, and it still doesn't work.
what's the issue with java date framework, it's really not straight forward.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该使用
java.sql.Timestamp
来存储
java .util.Date
中DATETIME
字段。如果您检查这两个类的 javadoc(单击上面的链接!),您将看到Timestamp
有一个 构造函数 以毫秒为单位计算时间,并且Date
有一个 getter 返回时间毫利斯。算一下:
您不应该不使用
java.sql.Date
因为它仅表示日期部分,而不表示时间部分。这样,您最终将在DATETIME
字段中得到00:00:00
作为时间。仅供您参考,由于
Timestamp
是java.util.Date
的子类,因此只要从ResultSet
获取它,您就可以向上转换它。You should use
java.sql.Timestamp
to store ajava.util.Date
in aDATETIME
field. If you check the javadocs of both classes (click the above links!), you'll see that theTimestamp
has a constructor taking the time in millis and thatDate
has a getter returning the time in millis.Do the math:
You should not use
java.sql.Date
as it represents only the date portion, not the time portion. With this, you would end up with00:00:00
as time in theDATETIME
field.For your information only, since
Timestamp
is a subclass ofjava.util.Date
, you could just upcast it whenever you obtain it from theResultSet
.这将做到这一点:
This will do it:
也许你可以尝试这个:
Maybe you can try this: