[英]Add to Database for each Row in JTable
I want to add into a database for each row from a Jtable.我想为 Jtable 中的每一行添加到数据库中。 eg 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) {
}
}
}
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) {
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.