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

Java使用JDateChooser操作MySQL插入正常更新报日期格式错误如何解决

问题原因
  • 执行更新操作时,你直接将Swing日期选择器的UI组件expirydate.getDateEditor().getUiComponent()、mandate.getDateEditor().getUiComponent()转为字符串拼接进SQL语句,输出的是Java默认的带时区的日期格式Wed Sep 08 00:00:00 PKT 2021,和MySQL日期字段要求的yyyy-MM-dd格式不匹配,因此触发数据截断报错。
  • 拼接SQL的写法还存在SQL注入风险,也容易因为字段内容包含特殊字符(比如描述里有单引号)导致SQL执行失败。
解决方法

方法1:手动格式化日期后拼接SQL(临时修复)

先把日期对象格式化为MySQL支持的yyyy-MM-dd格式,再拼到SQL语句中:

try{
    Class.forName("com.mysql.jdbc.Driver");
    Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/retailer","root","");
    // 新增日期格式化代码
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String expiryDateStr = sdf.format(expirydate.getDate());
    String mfDateStr = sdf.format(mandate.getDate());
    // 替换SQL里的日期部分为格式化后的字符串
    String query = "UPDATE stockable SET ProductName='"+productname.getText()+"',Quantity='"+quantity.getText()+"',SaleUnitPrice='"+saleprice.getText()+"',CurrentPurchasePrice='"+purchaseprice.getText()+"',ExpiryDate='"+expiryDateStr+"',MfturDate='"+mfDateStr+"',StockThesoldQty='"+thesoldqty.getText()+"',Description='"+desc.getText()+"' WHERE Productid ='"+n.getText()+"'";
    Statement ps = conn.createStatement();
    ps.execute(query);
    JOptionPane.showMessageDialog(null,"数据更新成功");
}
catch(Exception ex)
{
    JOptionPane.showMessageDialog(null,ex);
}

方法2:改用PreparedStatement(推荐,和插入逻辑保持一致)

和插入代码一样用预编译语句,无需手动处理日期格式,还能避免SQL注入风险,兼容性和安全性更高:

try{
    Class.forName("com.mysql.jdbc.Driver");
    Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/retailer","root","");
    String sql = "UPDATE stockable SET CategoryID=?, ProductName=?, Quantity=?, SaleUnitPrice=?, CurrentPurchasePrice=?, ExpiryDate=?, MfturDate=?, StockThesoldQty=?, Description=? WHERE Productid =?";
    PreparedStatement pst=conn.prepareStatement(sql);
    pst.setString(1,String.valueOf(cb1.getSelectedIndex()));
    pst.setString(2, productname.getText());
    pst.setString(3, quantity.getText());
    pst.setString(4, saleprice.getText());
    pst.setString(5, purchaseprice.getText());
    // 直接传入java.sql.Date类型,JDBC会自动适配MySQL日期格式
    pst.setDate(6, new java.sql.Date(expirydate.getDate().getTime()));
    pst.setDate(7, new java.sql.Date(mandate.getDate().getTime()));
    pst.setString(8, thesoldqty.getText());
    pst.setString(9,desc.getText());
    pst.setString(10, n.getText());
    int rs= pst.executeUpdate();
    if(rs>0){
        JOptionPane.showMessageDialog(null,"数据更新成功");
        // 此处可添加刷新表格的逻辑,和插入成功后的刷新逻辑保持一致即可
    }
}
catch(Exception ex)
{
    JOptionPane.showMessageDialog(null,ex);
}

补充说明:你原有的插入代码里直接用pst.setString传日期UI组件的写法也不规范,建议也改成setDate传入java.sql.Date类型,避免后续出现兼容性问题。

内容的提问来源于stack exchange,提问作者ahad nadeem

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 22:15:02