getValueAt() method returns null

巧了我就是萌 提交于 2019-12-11 11:29:42

问题


I am trying to save all the values of a defaulttablemodel to my sql database but whenever I put try to print the value on the last inserted row via table.valueAt(), it returns null.

try{
    System.out.print(table.getValueAt(5,0)); //<- this returns null even if the table.getRowCount() is 6

    for(int i=0; i<table.getRowCount();i++){
        if((Boolean)table.getValueAt(i,1)) val=1;
        else val=0; 
        //System.out.print(table.getValueAt(i, 0) +","+ val);
        String sql1 = "INSERT INTO HREmpListofCard (EmpID, CardNbr, Status, Remarks) VALUES ("
            +"'"+empID
            +"','"+table.getValueAt(i, 0).toString() 
            +"','"+val
            +"','"+table.getValueAt(i,2).toString()+"')";

        try {
            DBConnect.getConnection().createStatement().executeUpdate(sql1);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ListOfCardID.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(ListOfCardID.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}catch(Exception e){
    System.out.print("\nerror!");
}

回答1:


As for your second question. You can check your variable in your table before you put it inside your query. For example you can do this:

 String item1;

 if(table.getValueAt(i, 0) != null)
     item1 = table.getValueAt(i, 0);
 else
     item1 = null;

Replace item1 with you "table.getValueAt(i, 0)" and create an item2 for your "table.getValueAt(i,2)"

String sql1 = "INSERT INTO HREmpListofCard (EmpID, CardNbr, Status, Remarks) VALUES ("             
        +"'"+empID             
        +"','"+ITEM1
        +"','"+val             
        +"','"+ITEM2+"')";  

I haven't tested this, so I'm not sure if it will work :)

Good luck!



来源:https://stackoverflow.com/questions/10265880/getvalueat-method-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!