数据截断:日期时间值不正确:“”

2022-09-02 09:09:43

任何人都可以帮助我使用示例JSP代码通过JDBC将日期存储在MySql数据库中吗?当我尝试执行下面给出的代码时,我得到以下异常:

com.mysql.jdbc.MysqlDataTruncation: Data Truncation: 不正确的 datetime 值:“”表示第 1 行的“date”列

如何克服这个问题?以下是我的代码:

Connection con = null;

String StaffName = request.getParameter("StaffName");
// String subcode = request.getParameter("subcode");
String hourId = request.getParameter("hourId");
if (hourId == null)
    hourId = "";
String day = request.getParameter("day");
if (day == null)
    day = "";
String date = request.getParameter("date");
try {
    Class.forName("com.mysql.jdbc.Driver");
    con = DriverManager.getConnection("jdbc:mysql://localhost:3306/StaffAllocation", "root", "success");

    // PreparedStatement stat = con.PrepareStatement();
    String updateString = "INSERT INTO tblstaffallocation (StaffName,hourId,daysId,date) VALUES (?,?,?,?)";
    PreparedStatement preparedStatement = con.prepareStatement(updateString);

    preparedStatement.setString(1, StaffName);
    preparedStatement.setInt(2, 0);
    preparedStatement.setInt(3, 0);
    preparedStatement.setString(4, date);
} catch (Exception e) {
    out.print(e);
}

答案 1

要将日期设置为预准备语句,您需要更改值的类型:

String date = request.getParameter("date");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // your template here
java.util.Date dateStr = formatter.parse(date);
java.sql.Date dateDB = new java.sql.Date(dateStr.getTime());

现在将字符串日期转换为java.sql.Date并使用另一种方法:

preparedStatement.setDate(4,dateDB);

答案 2

我遇到了类似的错误。事实证明,我只需要更新mysql-connector-java的jar版本(使用maven)

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>...</version>
    </dependency>