【问题标题】:Add to Database for each Row in JTable为 JTable 中的每一行添加到数据库
【发布时间】:2016-03-31 17:06:11
【问题描述】:

我想将 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) {
        }
    }

}

【问题讨论】:

  • 是否要将Jtable中的所有行复制到数据库表中?
  • 是的,哪些产品已添加到 jTable 中
  • 使用循环有什么问题? for (int row = 0; row < resultsTable.getModel().getRowCount(); row++) { .. }
  • 我没有头,所以通过我不存在的头的嘴这么说?但是,……但是,……但是,……我没有头! try { ... } catch (HeadlessException e) { JOptionsPane.showMessageDialog(...); }#catch-22

标签: java sql database jtable


【解决方案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) {
        }
    }

}

【讨论】:

    猜你喜欢
    • 2014-09-24
    • 2015-07-10
    • 2016-11-12
    • 2011-10-12
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 2023-03-04
    相关资源
    最近更新 更多