2017-06-20 61 views
1

好吧,我做了一個新的更新Jtable代碼,但它不工作,你能幫我理解爲什麼嗎?當我更新JTable中的數據庫時,我得到了多個項目

下面的代碼:

private void update(){ 
     DefaultTableModel modelo = new DefaultTableModel(); 
     try{ 
      Connection lig; 
      lig = DriverManager.getConnection("jdbc:mysql://localhost/bdteste","root",""); 
      PreparedStatement inst; 
      inst = (PreparedStatement) lig.createStatement(); 
      ResultSet res; 
      res = inst.executeQuery("SELECT * FROM pessoa"); 
      while(res.next()){ 
       int id = res.getInt("ID"); 
       String descriçao = res.getString("Descriçao"); 
       double montante = res.getDouble("Montante"); 
       String categoria = res.getString("Categoria_Extrato"); 
       model.addRow(new Object[]{id, descriçao, montante, categoria}); 
      } 
        res.close(); 
     inst.close(); 
     lig.close(); 
     } 

     catch(SQLException ex){ 
       JOptionPane.showMessageDialog(null, "Erro na base de dados!"); 
     } 
     recdadostbl.setModel(modelo); 
    } 

而這裏發生了什麼: Me inserting the dataError1

+2

1)爲了更好地幫助更快,發佈[MCVE]或[短,自成一格,正確的例子](http://www.sscce.org/)。 2)使用合乎邏輯的一致形式縮進代碼行和塊。縮進旨在使代碼的流程更易於遵循! 3)IDE與問題無關。不要在標題中提及它,或者添加標籤。 –

回答

0

我想我找到了我的問題的解決方案。 當我進入我的錶板,我刪除了所有的表model.setRowCount(0);,然後我用這個方法重新插入所有新的和舊的數據,

public void updatetbl() 
{ 

    try { 
Connection lig; 
lig = DriverManager.getConnection("jdbc:mysql://localhost/financas","root",""); 
Statement inst; 
inst = lig.createStatement(); 
ResultSet res = inst.executeQuery("SELECT * FROM extrato"); 
    while(res.next()){ 
    int id = res.getInt("ID"); 
    String descriçao = res.getString("Descriçao"); 
    double montante = res.getDouble("Montante"); 
    String categoria = res.getString("Categoria_Extrato"); 
    model.addRow(new Object[]{id, descriçao, montante, categoria}); 

    } 

    } 
    catch(SQLException ex){ 
     JOptionPane.showMessageDialog(null,"Base de Dados Indisponivel"+ex); 
    } 
} 
相關問題