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

更新函数执行无报错但未修改数据库,求技术排查

问题描述

更新函数执行完成后未修改数据库,且无任何报错信息,项目即将在午夜截止,急需解决。

相关代码

按钮点击事件代码

private void Approve_btnActionPerformed(java.awt.event.ActionEvent evt) {                                            
        int bonus = Integer.parseInt(bonus_txt.getText());
            int sal = Integer.parseInt(salary_txt.getText());
            int sales = Integer.parseInt(sales_txt.getText());
            int net_sal= (bonus*sales)+sal;
            String netsal = Integer.toString(net_sal);
            String approve = "yes";

更新语句部分

try {        
            DBconn();
            ps = con.prepareStatement("update bonus_table set approved='"+approve+"',net_sal='"+netsal+"' where e_code='"+ecode_txt.toString()+"'and bcode='"+bcode+"'");
            ps.executeUpdate();
            tableData();

tableData()函数用于更新JTable显示最新数据,不属于问题范畴,未完整展示。

} catch (SQLException ex) {
            Logger.getLogger(ManagerApproval.class.getName()).log(Level.SEVERE, null, ex);
        }        
    }

数据库连接方法

public void DBconn(){
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bms_db","root","");
            ps = con.prepareStatement("select * from bonus_table");
            System.out.println(con);
        }
        catch(ClassNotFoundException ex){
            Logger.getLogger(BMS.class.getName()).log(Level.SEVERE,null,ex);
        }
        catch(SQLException ex){
            Logger.getLogger(BMS.class.getName()).log(Level.SEVERE,null,ex);
        }
    }

类内变量声明

Connection con;
    ResultSet rs;
    PreparedStatement ps;
问题排查与修复方案
  • 输入框取值错误:ecode_txt.toString()会返回组件的对象字符串(如javax.swing.JTextField[...]),而非输入内容,需改为ecode_txt.getText()。
  • SQL语法错误:where子句中and前缺少空格,原语句...e_code='xxx'and bcode='xxx'会导致解析失败,需改为...e_code='xxx' and bcode='xxx'。
  • PreparedStatement重复初始化:DBconn()中提前给ps赋值了查询语句,后续虽会覆盖,但易引发问题,建议DBconn()只负责建立连接,不初始化ps。
  • 事务与资源未处理:若MySQL未开启自动提交,需在executeUpdate()后添加con.commit();;同时要在finally块中关闭ps和con,避免连接泄漏。
  • 改用参数化查询:拼接SQL存在注入风险且易出错,推荐参数化写法:
    ps = con.prepareStatement("update bonus_table set approved=?, net_sal=? where e_code=? and bcode=?");
    ps.setString(1, approve);
    ps.setInt(2, net_sal); // 若net_sal是数值类型,用setInt更合适
    ps.setString(3, ecode_txt.getText());
    ps.setString(4, bcode);
    int rows = ps.executeUpdate();
    
  • 排查匹配数据:添加打印语句查看受影响行数System.out.println("受影响行数:" + rows);,若为0,说明where条件未匹配到数据,需检查e_code和bcode的实际值是否正确。

内容的提问来源于stack exchange,提问作者Allan Sharad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 13:20:35