为JTable中的每一行添加到数据库

时间:2016-03-31 17:06:12

标签: java sql database jtable

我想从Jtable中为每一行添加一个数据库。例如它添加了表格中的第一个产品,但我希望它添加每个产品。

 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) {
        }
    }

}

1 个答案:

答案 0 :(得分:1)

你需要创建一个迭代表中每一行的循环,如下所示:

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) {
        }
    }

}