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

ResultSet.updateTime()更新MySQL TIME字段值异常问题求助

问题排查与解决方案

这个问题的核心原因很明确——你误用了时间格式解析符:用12小时制的hh来解析24小时制的时间输入,导致时间解析出现隐性错误,虽然控制台输出看似正常,但实际存入数据库的时间已经偏离了预期。

具体分析

在SimpleDateFormat的规则里:

  • hh代表12小时制的小时(取值范围1-12)
  • HH才是24小时制的小时(取值范围0-23)

当你输入22:22:22这种24小时制时间时,用hh解析会触发SimpleDateFormat默认的宽松解析模式——它会把超出12的小时数强行转换成符合12小时制的数值,最终生成的Time对象内部时间戳已经出错。虽然Time.toString()可能按24小时制输出看似正确的结果,但实际数据库存储时,这个错误的时间戳会被转换为异常的时间值(也就是你看到的01:52:22)。

修正方案

把SimpleDateFormat的格式字符串从"hh:mm:ss"改为"HH:mm:ss",就能正确解析24小时制的时间输入了。修正后的代码如下:

System.out.println("Enter time: (HH:MM:SS)");
// 替换为HH:mm:ss,支持24小时制时间解析
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
try {
    Time tme = new Time(sdf.parse(in.nextLine()).getTime());
    System.out.println(tme);
    while(rs.next()) {
        System.out.println(rs.getString(2));
        System.out.println("New Time: " + tme);
        rs.updateTime(2, tme);
        rs.updateRow();
    }
} catch (ParseException e) {
    // 建议添加异常处理,捕获时间格式输入错误的情况
    e.printStackTrace();
}

额外优化建议

如果你用的是Java 8及以上版本,强烈推荐使用java.time系列API(替代老旧的SimpleDateFormat和Time类),它更安全、直观,能避免很多时间处理的坑:

System.out.println("Enter time: (HH:MM:SS)");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
try {
    LocalTime tme = LocalTime.parse(in.nextLine(), formatter);
    System.out.println(tme);
    while(rs.next()) {
        System.out.println(rs.getString(2));
        System.out.println("New Time: " + tme);
        // JDBC 4.2+支持直接更新LocalTime类型
        rs.updateObject(2, tme);
        rs.updateRow();
    }
} catch (DateTimeParseException e) {
    e.printStackTrace();
}

另外,建议检查你的Java程序和MySQL数据库的时区设置是否一致,避免因时区差异导致时间显示异常。

内容的提问来源于stack exchange,提问作者Alon Barenboim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 08:47:53