簡體   English   中英

為 JTable 中的每一行添加到數據庫

[英]Add to Database for each Row in 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) {
        }
    }

}

您需要創建一個循環來遍歷表中的每一行,如下所示:

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM