Java Swing ATM界面存款交易后数据库余额无法更新问题求助(含报错及代码)
修复ATM存款模块的数据库更新问题
嘿,我看到你在Java Swing开发的ATM项目里,遇到了存款后余额不更新还抛出parameter index out of range 1> number of parameters which is 0错误的问题,咱们一步步来排查修复:
核心问题分析与修复
1. 参数绑定对象错误(直接导致报错)
你在创建用于更新的PreparedStatement pst1后,错误地使用了之前查询用的pst来设置参数:
pst.setInt(1,cardnum); // 这里用错了对象!
正确的做法是用pst1来绑定update语句里的占位符:
pst1.setInt(1, cardnum);
2. SQL语句语法错误(导致更新失败)
你的update语句拼接后存在语法问题:
String sql = "update customerDetails set balance=balance+"+depositAmount+ "where cardnum=?";
注意depositAmount后面和where之间没有空格,拼接后会变成类似balance=balance+100where cardnum=?,数据库无法识别where关键字,必须添加空格:
String sql = "update customerDetails set balance=balance+"+depositAmount+ " where cardnum=?";
3. 避免SQL注入(优化建议)
直接把depositAmount拼接到SQL里存在SQL注入风险,建议也用占位符处理,更安全:
String sql = "update customerDetails set balance=balance+? where cardnum=?"; PreparedStatement pst1 = con.prepareStatement(sql); pst1.setInt(1, depositAmount); // 绑定存款金额 pst1.setInt(2, cardnum); // 绑定卡号
4. 资源泄漏问题(额外优化)
你的代码没有关闭数据库连接、Statement、ResultSet等资源,长期运行会导致连接泄漏,建议用try-with-resources语法自动关闭资源,代码更健壮。
修复后的完整代码片段
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed try { int depositAmount = Integer.valueOf(jTextField1.getText()); int cardnum = Integer.valueOf(jTextField2.getText()); Class.forName("com.mysql.jdbc.Driver"); try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/TYProject","root","riddhimore")) { // 查询用户信息 String querySql = "select * from customerDetails where cardnum=?"; try (PreparedStatement pst = con.prepareStatement(querySql)) { pst.setInt(1, cardnum); try (ResultSet rs = pst.executeQuery()) { if (rs.next()) { // 执行余额更新 String updateSql = "update customerDetails set balance=balance+? where cardnum=?"; try (PreparedStatement pst1 = con.prepareStatement(updateSql)) { pst1.setInt(1, depositAmount); pst1.setInt(2, cardnum); int updateCount = pst1.executeUpdate(); if (updateCount == 1) { int a = JOptionPane.showConfirmDialog(this, "Are you sure you want to submit ?", "Confirm ?", JOptionPane.YES_NO_CANCEL_OPTION); if (a == 0) { new atmFrame10().setVisible(true); this.setVisible(false); } } } } } } } } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage()); e.printStackTrace(); // 打印堆栈信息,方便排查更详细的错误 } }
内容的提问来源于stack exchange,提问作者Riddhi
相关产品推荐
相关产品推荐

