0

我正在尝试在 netbeans 上运行以下代码,但它抛出此错误“您的 SQL 语法有错误;请检查与您的 MySQL 服务器版本相对应的手册,以获取在 '?, esalary=?, eage 附近使用的正确语法=?, egender=?, edept=? 其中 eid = ?' 在第 1 行"。请帮我解决错误

private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
        try{
            //open connection
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?useSSL=false","root","BakerStreet@221b");
            
        
               //mysql query to update
               String sql = "update emp set ename=?, esalary=?, eage=?, egender=?, edept=? where eid = ?";
            PreparedStatement ptsmt = con.prepareStatement(sql);
              ptsmt.executeUpdate(sql);
              ptsmt.setString(1,empName.getText());
              ptsmt.setInt(2,Integer.parseInt(empSal.getText()));
              ptsmt.setInt(3,Integer.parseInt(empAge.getText()));
              ptsmt.setString(4,empGen.getText());
               ptsmt.setString(5,empDep.getText());
                ptsmt.setInt(6,Integer.parseInt(id.getText()));
              
          
              
              ptsmt.executeUpdate();
      
       
                JOptionPane.showMessageDialog(this, "Record updated Successfully");
        
               con.close();
        }
            catch(Exception e){
            System.out.println(e.getMessage());
        }
    }     

             
4

1 回答 1

0
  1. 你已经调用了两次 executeUpdate(sql) 所以删除一个
  2. 您在向参数添加值之前调用了 executeUpdate(sql),因此请执行以下操作:

private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO 在此处添加您的处理代码:try{ //打开连接 Class.forName("com.mysql.jdbc.Driver"); 连接 con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?useSSL=false","root","BakerStreet@221b");

           //mysql query to update
           String sql = "update emp set ename=?, esalary=?, eage=?, egender=?, edept=? where eid = ?";
        PreparedStatement ptsmt = con.prepareStatement(sql);
        
          ptsmt.setString(1,empName.getText());
          ptsmt.setInt(2,Integer.parseInt(empSal.getText()));
          ptsmt.setInt(3,Integer.parseInt(empAge.getText()));
          ptsmt.setString(4,empGen.getText());
           ptsmt.setString(5,empDep.getText());
            ptsmt.setInt(6,Integer.parseInt(id.getText()));
          
      
          //execute update ...
            ptsmt.executeUpdate();
  
   
            JOptionPane.showMessageDialog(this, "Record updated Successfully");
    
           con.close();
    }
        catch(Exception e){
        System.out.println(e.getMessage());
    }
}     
于 2021-07-08T18:58:43.733 回答