1

I have been trying to add multiple rows from JTable to my MySQL Database, but only the first row is registered and not the rest.

Here's my code:

 DefaultTableModel tblmodel= (DefaultTableModel) jTable1.getModel();
  
 
  if (tblmodel.getRowCount()==0)
  {
      JOptionPane.showMessageDialog(this, "Table is Empty");
      }
  else {
            
      try
      {
          Class.forName("com.mysql.jdbc.Driver");

          Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","123456");
          
      
      for (int i=0; i<tblmodel.getRowCount(); i++)
      {
          String pid = (String)jTable1.getValueAt(i, 0);
    String pname = (String)jTable1.getValueAt(i, 1);
    int price = (int)jTable1.getValueAt(i, 2);
    int qty = (int)jTable1.getValueAt(i, 3);
    int tprice = (int)jTable1.getValueAt(i, 4);
    
    String query = "Insert into invoice(product_id, product_name, price,quantity, total_price) values (?,?,?,?,?)";
 PreparedStatement ps;
    ps = con.prepareStatement(query);
   
    
    
     ps.setString(1, pid);
    ps.setString(2, pname);
    ps.setInt(3, price);
    ps.setInt(4, qty);
    ps.setInt(5, tprice);
          ps.execute();
          JOptionPane.showMessageDialog(this , "Data added Successfully");
          tblmodel.setRowCount(0);
          
      }
      } catch (Exception e) {
          
          }
3
  • why are u setting the rowcount to zero? Commented Nov 5, 2021 at 17:04
  • 1
    @halfer Apologies. I'm new to stack and I'm not quite familiar with the rules. I'll ensure that this would not happen in he foreseeable future. Commented Nov 7, 2021 at 17:28
  • Thanks Joshua! The idea with Stack Overflow is that questions (and their answers) become almost like documentation, and so succinct technical writing is preferred - ideally tailored to broad/general cases as much as possible. Commented Nov 7, 2021 at 17:31

1 Answer 1

1

This line of code

tblmodel.setRowCount(0)

is causing it to break out of the loop after the first iteration.

Sign up to request clarification or add additional context in comments.

4 Comments

I used it to reset the JTable after it was done saving.
reset a table means to clear it. is that what you want?
Yes, I removed tblmodel.setRowCount (0) and it worked perfectly fine, but I am now unable to clear the jTable as this function used to clear it.
I'm not sure exactly when you want to clear it but how about clearing it after you are out of the for loop?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.