我試圖使用ArrayList將值傳遞給數據庫。 後來我一個例外java.lang.ClassCastException: java.lang.String cannot be cast to model.OrderModel
這裏是我是如何讓用戶 值可有人請檢查並幫助我做到這一點如何使用oop概念傳遞不同數據類型的ArrayList對象?
DefaultTableModel dtm = (DefaultTableModel) tblOrder.getModel();
int numRow = dtm.getRowCount();
int numCol = dtm.getColumnCount();
try {
ArrayList<OrderModel> list = new ArrayList<OrderModel>();
for(int l = 0;l<numRow;l++){
for(int j=0;j<numCol;j++){
list.add((OrderModel) tblOrder.getValueAt(l, j));//this line may be the problem as i think
}
}
Order or = new Order();
or.passingValuesToDB(list);
} catch (Exception e) {
e.printStackTrace();
}
}
,這是我在
public class Order {
Connection con;
public void passingValuesToDB(ArrayList<OrderModel> list) {
try {
con = new DBconnector().connect();
String sql = "INSERT INTO order (orderid, customername, item, qty, amount, total) VALUES (?,?,?,?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);
for(int i=0;i<list.size();i++){
ps.setInt(1, list.get(i).getOrderid());
ps.setString(2, list.get(i).getCustomername());
ps.setString(3, list.get(i).getItem());
ps.setDouble(4, list.get(i).getQty());
ps.setDouble(5, list.get(i).getAmount());
ps.addBatch();
}
ps.executeQuery();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
而我的方法已將所有獲得者設置爲OrderModel類別& Setteres。這裏的代碼
public class OrderModel {
private int orderid;
private String customername;
private String item;
private double qty;
private double amount;
private double total;
public OrderModel(int orderid,String customername,String item,Double qty,Double amount,Double total){
this.orderid = orderid;
this.customername = customername;
this.item = item;
this.qty = qty;
this.amount=amount;
this.total=total;
}
public OrderModel() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public int getOrderid() {
return orderid;
}
public void setOrderid(int orderid) {
this.orderid = orderid;
}
public String getCustomername() {
return customername;
}
public void setCustomername(String customername) {
this.customername = customername;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public double getQty() {
return qty;
}
public void setQty(double qty) {
this.qty = qty;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
}
請告訴我有你的tblOrder,將您張貼類和堆棧跟蹤,以及是有幫助的。 –
是否確定tblOrder包含'OrderModel'實例? –
tblOrder只包含(itemName,數量,價格,金額) –