这是我用于将数据从jtable插入数据库的代码:
for(int i=1 ; i <= table.getRowCount() ; i++){
String productid = table.getValueAt(i, 0).toString();
String name = table.getValueAt(i, 1).toString();
String quantity = table.getValueAt(i, 2).toString();
String totalprice = table.getValueAt(i, 4).toString();
try {
String query = "insert into sales (productid,customerid,name,quantity,discount,totalprice,paymentmethod) values (?,?,?,?,?,?,?)";
pst = con.prepareStatement(query);
pst.setString(1, productid);
pst.setString(2, customerid.getText());
pst.setString(3, name);
pst.setString(4, quantity);
pst.setString(5, discount.getText()+"%");
pst.setString(6, String.valueOf(totalprice));
pst.setString(7, paymethod.getSelectedItem().toString());
pst.execute();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
当我点击按钮时保存它会给我一个错误。
线程“AWT-EventQueue-0”中的异常 java.lang.ArrayIndexOutOfBoundsException:1&gt; = 1 at java.util.Vector.elementAt(未知来源)at javax.swing.table.DefaultTableModel.getValueAt(未知来源)at javax.swing.JTable.getValueAt(未知来源)at gestioner.Sale $ 8.actionPerformed(Sale.java:332)at javax.swing.AbstractButton.fireActionPerformed(未知来源)
答案 0 :(得分:2)
通过Deafault表模型
进行迭代public String getTableData (JTable table) {
DefaultTableModel dtm = (DefaultTableModel) table.getModel();
int nRow = dtm.getRowCount(), nCol = dtm.getColumnCount();
String tableData = " ";
for (int i = 0 ; i < nRow ; i++)
for (int j = 0 ; j < nCol ; j++)
// tableData = dtm.getValueAt(i,j);
String productid = table.getValueAt(i, j).toString();
String name = table.getValueAt(i, j).toString();
String quantity = table.getValueAt(i, j).toString();
String totalprice = table.getValueAt(i, j).toString();
try {
String query = "insert into sales (productid,customerid,name,quantity,discount,totalprice,paymentmethod) values (?,?,?,?,?,?,?)";
pst = con.prepareStatement(query);
pst.setString(1, productid);
pst.setString(2, customerid.getText());
pst.setString(3, name);
pst.setString(4, quantity);
pst.setString(5, discount.getText()+"%");
pst.setString(6, String.valueOf(totalprice));
pst.setString(7, paymethod.getSelectedItem().toString());
pst.execute();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return tableData;
}
答案 1 :(得分:1)
基于错误消息,“ArrayIndexOutOfBoundsException”您试图读取行范围之外的项目;你的for循环应该从0开始而不是1,并且在row-count之前停止,你的for循环应该如下所示:
for(int i=0 ; i <table.getRowCount() ; i++){...