Miguel Bestia
Miguel Bestia

Reputation: 19

jTable update button and add new

Below is my code of a jFrame btn_update:

private void txt_updateActionPerformed(java.awt.event.ActionEvent evt) {                                           
    try{
        String Value1=txt_Emp_ID.getText();
        String Value2=txt_Name.getText();
        String Value3=txt_Surname.getText();
        String Value4=txt_age.getText();
        String Value5=txt_Username.getText();
        String Value6=txt_Password.getText();

        String sql = "update employee set Emp_ID=?, name=?,surname=?,age=?,username=?,password=?";           
        pst.setString(1, Value1);
        pst.setString(2, Value2);
        pst.setString(3, Value1);
        pst.setString(4, Value1);
        pst.setString(5, Value1);
        pst.setString(6, Value1);
        pst=conn.prepareStatement(sql);
        rs=pst.executeQuery();
        JOptionPane.showMessageDialog(null, "Updated!!");
    }catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
}                                    

and my configurations:

Connection conn=null;
ResultSet rs = null;
PreparedStatement pst = null;

when I try to press the update button I get this:

java.sql.SQLException:Parameter index out of Range (2>number of parameters, which is 1) can someone help me?

Upvotes: 1

Views: 55

Answers (1)

Reimeus
Reimeus

Reputation: 159754

A few issues

  • Your exception message indicates that the PreparedStatement only has 2 parameters. Assign the variable before setting the parameters
  • Copy/paste error where parameters 3-6 are all Value1 instead of Value3, Value4, etc.
  • executeQuery is used to query the database. Use executeUpdate for database write operations

Result:

preparesStatement = connection.prepareStatement(sql);
preparesStatement.setString(1, value1);
...// etc.
preparesStatement.setString(6, value6);

Upvotes: 2

Related Questions