You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MySQL日期插入报错:Data truncation,表单提交日期不被数据库接受

解决MySQL日期插入错误:Data truncation: Incorrect date value

问题根源

MySQL的DATE类型字段默认只接受**YYYY-MM-DD格式的字符串,你传入的'1/1/2000'(短格式带斜杠)不符合要求,导致数据库无法解析,触发截断错误。另外你的代码直接拼接SQL字符串,存在严重的SQL注入风险**,同时也会放大格式兼容问题。

两种解决方案

方案1:使用PreparedStatement(推荐,安全且规范)

通过Java解析前端输入的日期字符串,转换为SQL兼容的Date对象后绑定参数,彻底避免格式问题和注入风险:

String s1 = stdid.getText();
String s2 = name.getText();
String s3 = dob.getText();
String s6 = (String) combogender.getSelectedItem();
String s4 = email.getText();
String s7 = txtpassword.getText();
String s5 = contact.getText();

try {
    Class.forName("com.mysql.jdbc.Driver");
    con = DriverManager.getConnection(cs, user, password);
    
    // 1. 解析前端日期字符串(根据实际输入格式调整格式符,比如MM/dd/yyyy或dd/MM/yyyy)
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    LocalDate dobLocalDate = LocalDate.parse(s3, formatter);
    java.sql.Date sqlDob = java.sql.Date.valueOf(dobLocalDate);
    
    // 2. 使用PreparedStatement绑定参数
    String query = "INSERT INTO student(studentid, Name, DOB, gender, email, password, contact) VALUES (?, ?, ?, ?, ?, ?, ?)";
    PreparedStatement pst = con.prepareStatement(query);
    pst.setString(1, s1);
    pst.setString(2, s2);
    pst.setDate(3, sqlDob);
    pst.setString(4, s6);
    pst.setString(5, s4);
    pst.setString(6, s7);
    pst.setString(7, s5);
    
    pst.executeUpdate();
} catch (Exception e) {
    e.printStackTrace(); // 实际开发中替换为业务友好的异常处理
} finally {
    // 务必关闭资源,避免连接泄漏
    try {
        if (pst != null) pst.close();
        if (con != null) con.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

注:如果使用Java 8以下版本,用SimpleDateFormat替代DateTimeFormatter,但要注意SimpleDateFormat非线程安全,需避免复用实例。

方案2:用MySQL函数转换格式(不推荐,仍有注入风险)

如果临时不想修改Java代码结构,可以在SQL中用STR_TO_DATE函数将输入的日期字符串转换为MySQL兼容格式:

// 仅修改SQL部分,注意格式符要和前端输入匹配(%m=月份,%d=日期,%Y=4位年份)
query = "INSERT INTO student(studentid,Name,DOB,gender,email,password,contact) VALUES('"+s1+"','"+s2+"',STR_TO_DATE('"+s3+"', '%m/%d/%Y'),'"+s6+"','"+s4+"','"+s7+"','"+s5+"')";

关键注意事项

  • 确认前端输入的日期格式:如果是日/月/年顺序,格式符要改为%d/%m/%Y
  • 永远优先使用PreparedStatement,禁止直接拼接用户输入到SQL中,防止SQL注入攻击
  • 异常处理和资源关闭必须完善,避免数据库连接泄漏

内容的提问来源于stack exchange,提问作者John Wycliffe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 00:52:42