zayn94
zayn94

Reputation: 65

Add to Database for each Row in JTable

I want to add into a database for each row from a Jtable. e.g. It adds the first product in the table but I want it to add each one.

 private void addToInvoiceLine(){
 try {
        String sql = "Insert Into invoiceLine (invoiceID,SKU,quantity) values (?,?,?)";
        pst = conn.prepareStatement(sql); 
        int row = resultsTable.getSelectedRow();

        String sku = (orderTable.getModel().getValueAt(row, 0).toString());
        String quantity = (orderTable.getModel().getValueAt(row, 2).toString());
        pst.setString(1, invoiceNo.getText());
        pst.setString(2, sku);
        pst.setString(3, quantity);

        pst.execute();


    } catch (SQLException | HeadlessException e) {

        JOptionPane.showMessageDialog(null, e);
    } finally {
        try {
            rs.close();
            pst.close();
        } catch (Exception e) {
        }
    }

}

Upvotes: 1

Views: 146

Answers (1)

Magnus
Magnus

Reputation: 18738

You need to make a loop that iterates over each row in the table, like this:

private void addToInvoiceLine(){
    try {
        String sql = "INSERT INTO invoiceLine (invoiceID,SKU,quantity) VALUES (?,?,?)";
        pst = conn.prepareStatement(sql); 


        for(int row=0; row<orderTable.getModel().getRowCount(); row++){
            String sku = orderTable.getModel().getValueAt(row, 0).toString();
            String quantity = orderTable.getModel().getValueAt(row, 2).toString();

            pst.setString(1, invoiceNo.getText());
            pst.setString(2, sku);
            pst.setString(3, quantity);

            pst.execute();
        }


    } catch (SQLException | HeadlessException e) {
        JOptionPane.showMessageDialog(null, e);
    } finally {
        try {
            rs.close();
            pst.close();
        } catch (Exception e) {
        }
    }

}

Upvotes: 1

Related Questions