1

I have a .jsp page that has a multi checkbox. I'm able to insert the multiple checkbox values but when use an update, it adds the current checkbox rows plus the additional checkbox value rows. If I check one more box it should add 1 more row and so on.

Here is my code that works for update: CollDAO.java:

//Insert checkbox records
public void addColl(String qId, String[] arrayColId) {
  try {
    PreparedStatement ps = con.preparedStatement("insert into colTable(qId, colId) values(?,?)");

   for(int i = 0; i < arrayColId.length; i++) {
     ps.setString(1, qId);
     ps.setString(2, arrayColId[i]);
     ps.executeUpdate();
   }
  } catch (SQLException e) {
     e.printStackTrace();
  }
}

If I select 2 checkboxes this is what it looks like.

rowid | qID | cID -- CORRECT

:101: | :121: | :9:

:100: | :121: | :13:

//Update checkbox records
public void updateColl(String qId, String[] arrayColId) {
  try {
    String sql = "update colTable set colId=?, where qId=?";
   PreparedStatement ps = con.preparedStatement(sql);

   for(int i = 0; i < colId; i++) {
     ps.setString(1, colId[i]);
     ps.setString(2, qId);
     ps.executeUpdate();
   }

  } catch (SQLException e) {
     e.printStackTrace();
  }
}

If I select 3 checkboxes this is what get updated.

rowid | qID | cID -- WRONG OUTPUT

:105: | :121: | :2:

:104: | :121: | :9:

:103: | :121: | :13:

:101: | :121: | :9:

:100: | :121: | :13:

This is what it suppose to look like.

rowid | qID | cID -- CORRECT OUTPUT

:103: | :121: | :2:

:101: | :121: | :9:

:100: | :121: | :13:

I've been working on this for a week, can someone help me?

Thank you

Gee
  • 155
  • 2
  • 6
  • 21

1 Answers1

0

In your case you should to use Batch instead :

PreparedStatement ps = con.preparedStatement("your query");

for(int i = 0; i < arrayColId.length; i++) {
     ps.setString(1, qId);
     ps.setString(2, arrayColId[i]);
     ps.addBatch();    
}

ps.executeBatch();

You can learn more here Reusing a PreparedStatement multiple times and Statament batching

Edit

For your update you can use :

connection.setAutoCommit(false);

int arrayVals = Math.min(arrayColId.length, arrayQId.length);
for (int i = 0; i < arrayVals; i++) {
    ps.setString(1, arrayColId[i]);
    ps.setString(2, arrayQId[i]);
    ps.addBatch(); //add a batch
}

ps.executeBatch();//execute your batch

connection.commit();//when you finish you should to commit your transaction
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140