JDBC 和 MySQL,如何将 java.util.Date 持久保存到 DATETIME 列?

发布于 2024-12-07 20:31:48 字数 116 浏览 0 评论 0原文

我正在努力了解如何让它发挥作用。我有一个准备好的语句,我想保留一个 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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

孤凫 2024-12-14 20:31:48

您应该使用 java.sql.Timestamp来存储 java .util.DateDATETIME 字段。如果您检查这两个类的 javadoc(单击上面的链接!),您将看到 Timestamp 有一个 构造函数 以毫秒为单位计算时间,并且 Date 有一个 getter 返回时间毫利斯。

算一下:

preparedStatement.setTimestamp(index, new Timestamp(date.getTime()));
// ...

您不应该使用java.sql.Date 因为它仅表示日期部分,而不表示时间部分。这样,您最终将在 DATETIME 字段中得到 00:00:00 作为时间。

仅供您参考,由于 Timestampjava.util.Date 的子类,因此只要从 ResultSet 获取它,您就可以向上转换它。

Date date = resultSet.getTimestamp("columnname");
// ...

You should use java.sql.Timestamp to store a java.util.Date in a DATETIME field. If you check the javadocs of both classes (click the above links!), you'll see that the Timestamp has a constructor taking the time in millis and that Date has a getter returning the time in millis.

Do the math:

preparedStatement.setTimestamp(index, new Timestamp(date.getTime()));
// ...

You should not use java.sql.Date as it represents only the date portion, not the time portion. With this, you would end up with 00:00:00 as time in the DATETIME field.

For your information only, since Timestamp is a subclass of java.util.Date, you could just upcast it whenever you obtain it from the ResultSet.

Date date = resultSet.getTimestamp("columnname");
// ...
自由如风 2024-12-14 20:31:48

这将做到这一点:

int dateColumnId = 0; // or whatever the value needs to be.
java.util.Date incomingValue = new java.util.Date(System.currentTimeMillis());
java.sql.Date databaseValue = new java.sql.Date(incomingValue.getTime());   
ps.setDate(dateColumnId, databaseValue);

This will do it:

int dateColumnId = 0; // or whatever the value needs to be.
java.util.Date incomingValue = new java.util.Date(System.currentTimeMillis());
java.sql.Date databaseValue = new java.sql.Date(incomingValue.getTime());   
ps.setDate(dateColumnId, databaseValue);

也许你可以尝试这个:

java.util.Date now = new java.util.Date();
java.sql.Date date = new java.sql.Date(now.getTime());
pstmt.setDate(columnIndex,date);

Maybe you can try this:

java.util.Date now = new java.util.Date();
java.sql.Date date = new java.sql.Date(now.getTime());
pstmt.setDate(columnIndex,date);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文