【问题标题】:pass LocalTime to PreparedStatement将 LocalTime 传递给 PreparedStatement
【发布时间】:2020-02-21 20:39:37
【问题描述】:

我想将 java 本地时间传递给 PreparedStatement (java.sql.),如下所示:

ps.setTimestamp(id++, (localtime));

我不知道setTimestamp 是否正确,或者我是否应该使用setTime 甚至是另一个。我没有找到一个直接适合本地时间的,那么如何转换它以便将其传递给 Preparedstatement?

【问题讨论】:

  • 取决于数据库中的列有什么数据类型...是哪一种?时间戳是日期时间(日期和时间)或以毫秒为单位的瞬间表示。可能还有更多的可能性。
  • 您可以将所有时间数据转换为纪元时间并将其传递到准备好的语句中
  • @MadScientist 但datetime 不是time。
  • @MadScientist 如果您不打算使用日期部分,那么拥有 datetime 列是没有意义的。
  • @MadScientist 然后与其他人交谈。您不能只是劫持一个列并决定将其用作不同的类型。如果列是datetime,那么您必须将其用作datetime。听起来您正在尝试做错事,因此请在破坏某些内容之前询问您的同事。

标签: java time timestamp prepared-statement


【解决方案1】:

PreparedStatement 中有 setTime(Time x) 方法,您可以将 LocalTime 转换为 java.sql.Time:

LocalTime localTime = localTime.now();
preparedStatement.setTime(1, Time.valueOf(localTime);

编辑
如果您在数据库中的数据类型是DateTime,那么您必须传递完整的时间戳,即java.sql.Timestamp,其中还包括有关日期的信息,而不仅仅是时间。

如果您想使用java.time,那么您可以使用LocalDateTime 而不仅仅是LocalTime,并将其转换为时间戳(反之亦然):

LocalDateTime now = LocalDateTime.now();
preparedStatement.setTimestamp(1, Timestamp.valueOf(now));

如果您在数据库列中有DATETIME 的数据类型,并且您想将时间设置为LocalTime,请使用LocalDate.now() 以创建具有LocalTime 的LocalDateTime 实例,然后添加它作为查询参数:

// use your instance of LocalTime (now() is just an example)
LocalTime timeNow = LocalTime.now();
// get the date of today (or maybe another specific one)
LocalDate today = LocalDate.now();
// combine them
LocalDateTime now = LocalDateTime.of(today, timeNow);
// add the converted combination as parameter
preparedStatement.setTimestamp(1, Timestamp.valueOf(now));

【讨论】:

  • 假设提问者使用的是符合 JDBC 4.2 的驱动程序,没有理由使用设计不佳且早已过时的Timestamp 类。 preparedStatement.setObject(1, now);(其中now 是您的LocalDateTime 对象)。
  • @OleV.V 我知道,但是当我添加这个作为替代时已经回答了。
【解决方案2】:

您可以将PreparedStatement 和ResultSet 中的java.time 类与set/getObject 方法一起使用,因为(目前)没有针对这些类型的特定方法。数据库驱动程序也需要足够新以支持这些。

ps.setObject(1, localtime);
LocalTime loco = rs.getObject(1, LocalTime.class);

列类型当然也需要正确。

【讨论】:

    猜你喜欢
    • 2012-09-26
    • 2013-06-10
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多