【问题标题】:(JAVA) Need to convert DATE to prepared statement for SQL(JAVA) 需要将 DATE 转换为 SQL 的准备语句
【发布时间】:2020-03-04 16:29:53
【问题描述】:

在过去的一个小时里,我一直在寻找并尝试在网络(和 SO)上提供的解决方案,了解如何在 Java 中使用 Date 类型,但我似乎无法让它工作。我使用的是 NetBeans 11.2,但我习惯了 Java,这让我很难受(不是双关语)。看来LocalDateTimeDateTime 已贬值,我应该使用java.time

说实话,我不知道该怎么办了。我正在尝试使用输入值构建一个查询以保存在mySQL 数据库中。

日期来源来自<input type="date">

SignIn.java (servlet)

String birthDate = request.getParameter("data_birthdate");

UserDto userDto = null;
UserDao userDao = new UserDao(); 

try 
{ 
// Tried this 
    userDto = userDao.CreateUser(LocalDateTime.parse(birthDate));
// Tried that
    userDto = userDao.CreateUser(Date.parse(birthDate));
// Tried this 
    userDto = userDao.CreateUser(Time.parse(birthDate));
}

userDao.java(道)

public void CreateUser(Date dateBirth) throws SQLException {
try {
        connect = db.getConnect();
        ps = connect.prepareStatement(SQL_CreateUser);
        ps.setDate(1, dateBirth);
        ps.executeUpdate();
    }
}

【问题讨论】:

标签: java sql date netbeans


【解决方案1】:

您可以将LocalDateTimePreparedStatement#setTimestamp() 一起使用。以下是您的大致方法:

String birthDate = request.getParameter("data_birthdate");
// assuming your text birthdates look like 1980-12-30 00:30:05
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dt = LocalDateTime.parse(birthDate, formatter);

try {
    connect = db.getConnect();
    ps = connect.prepareStatement(SQL_CreateUser);
    ps.setTimestamp(3, Timestamp.valueOf(dt));
}
catch (Exception e) {
    // handle exception
}

请注意在调用DateTimeFormatter#ofPattern 时使用的格式掩码。您需要将其替换为实际适合您的字符串日期的任何掩码。

【讨论】:

  • (1) 如果 SQL 中的数据类型是 timestamp with time zone(推荐),则在 Java 中使用 offsetDateTime 和/或 Instant。 (2) 即使没有,也要避免Timestamp,使用ps.setObject(3, dt);
猜你喜欢
  • 2021-05-09
  • 2011-08-31
  • 2021-11-11
  • 2018-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多