下面的代码是我在销售后用新的剩余库存数量更新数据库的方法。
在我的表单中,表有动态行。意味着用户可以按自己的意愿添加1或更多。
因此,我使用for循环来获取当前表行并从表中获取相关的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");
}
}但代码抛出的例外如下;
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);。帮我解决这个错误。

发布于 2015-08-22 10:57:15
替换这一行
for(int rcount=0;rcount<=tableSale.getRowCount();rcount++){有了这个
for(int rcount=0;rcount<tableSale.getRowCount();rcount++){当索引从0开始计数时,如果行数为1,则最大索引将为0。它将崩溃索引1,这将解决问题。
好的,上面的问题是有效的,另一件事是
rcount =tableSale.getRowCount()
rcount是您的循环变量。为什么要给它分配表行计数。行计数总是最大的,index+1 t总是会导致索引超出界限。删除这一行,然后检查。
发布于 2019-10-07 14:28:04
for(int rcount=0;rcount<tblProduct.getRowCount();rcount++){
String idsale = (String) tblProduct.getModel().getValueAt(rcount, 0);
String sql0= "select * from productsinformation where ProductID=?";
stm=conn.prepareStatement(sql0);
stm.setString(1, idsale);
ResultSet rs= stm.executeQuery();
if(rs.next()){
String instock = rs.getString("Stock");
int nowstock=Integer.parseInt(instock);
int newstock = nowstock - 1;
String sqlupdate= "update productsinformation set Stock='"+newstock+"' where ProductID='"+idsale+"'";
stm=conn.prepareStatement(sqlupdate);
stm.execute();
}
}https://stackoverflow.com/questions/32155147
复制相似问题