【发布时间】:2015-08-22 10:38:57
【问题描述】:
以下代码是我在销售后用新的剩余库存数量更新数据库的方法。
在我的表单中,tablesale 具有动态行。表示用户可以根据需要添加 1 个或多个。
所以我使用for循环来获取当前表行并从tablesale中获取相关的ItemID并在db中搜索它,最后减少销售数量并将结果更新到数据库。
我的代码;
//redusing stock in db
for(int rcount=0;rcount<=tableSale.getRowCount();rcount++){
rcount = tableSale.getRowCount();
String idsale = (String) tableSale.getModel().getValueAt(rcount, 0);
String sql0= "select * from druginfo where ItemID=?";
pst0=conn.prepareStatement(sql0);
pst0.setString(1, idsale);
rs0= pst0.executeQuery();
if(rs0.next()){
String instock = rs0.getString("InStock");
int nowstock=Integer.parseInt(instock);
int soldqty = (int) tableSale.getModel().getValueAt(rcount, 3);
int newstock = nowstock - soldqty;
System.out.println("new :"+newstock);
String sqlupdate= "update druginfo set InStock='"+newstock+"' where ItemID='"+idsale+"'";
pst=conn.prepareStatement(sqlupdate);
pst.execute();
System.out.println("Done");
}
}
但是 Codes 会抛出如下异常;
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1 >= 1
at java.util.Vector.elementAt(Vector.java:474)
at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:648)
at com.bit.project.Newsale.saveprint_btnActionPerformed(Newsale.java:1009)
at com.bit.project.Newsale.access$1300(Newsale.java:57)
at com.bit.project.Newsale$16.actionPerformed(Newsale.java:651)
第 1009 行是String idsale = (String) tableSale.getModel().getValueAt(rcount, 0);。帮我解决这个错误。
【问题讨论】:
-
tableSale所属的 List 是什么? -
见this答案
-
您的异常清楚地表明您正在尝试访问表格中不存在的那些元素。如果我在
JTable中没有错,请告诉我您的总行/列数 -
@SubodhJoshi 我添加了截图。如您所见,用户可以根据需要添加许多行。