2015-04-07 69 views
0

拉動了數據我想從Access數據庫提取數據並填充,用下面的代碼問題在從ACCESSDB

String[] tableColumnsName = {"col 1","col 2","col 3"}; 
    DefaultTableModel aModel = (DefaultTableModel) jTable2.getModel(); 
    aModel.setColumnIdentifiers(tableColumnsName); 
    try { 
     // the query 
     rs = db.query("SELECT * FROM Students "); 
    } catch (SQLException ex) { 
     Logger.getLogger(RegisterGUI.class.getName()).log(Level.SEVERE, null, ex); 
    } 

    // Loop through the ResultSet and transfer in the Model 
    java.sql.ResultSetMetaData rsmd = null; 
    try { 
     rsmd = rs.getMetaData(); 
    } catch (SQLException ex) { 
     Logger.getLogger(RegisterGUI.class.getName()).log(Level.SEVERE, null, ex); 
    } 
    //int colNo = rsmd.getColumnCount(); 
    try { 
     while(rs.next()){ 
     Object[] objects = new Object[10]; 
     // tanks to umit ozkan for the bug fix! 
     for(int i=0;i<10;i++){ 
     objects[i]=rs.getObject(i+1); 
     } 
     aModel.addRow(objects); 
     } 
    } catch (SQLException ex) { 
     Logger.getLogger(RegisterGUI.class.getName()).log(Level.SEVERE, null, ex); 
    } 
    jTable2.setModel(aModel); 
}//GEN-LAST:event_jButton2ActionPerformed 

我能夠從一個提取數據。我怎樣才能從另一張桌子上拉出來?

回答

2

您對數據做了很多假設,並在完成相關工作後將資源打開。

首先,你應該使用ResultSetMetaData建立TableModel列信息,那麼你應該用它來從ResultSet建行數據,例如...

DefaultTableModel aModel = new DefaultTableModel(); 
try (ResultSet rs = db.query("SELECT * FROM Students ")) { 
    ResultSetMetaData rsmd = rs.getMetaData(); 
    for (int col = 0; col < rsmd.getColumnCount(); col++) { 
     aModel.addColumn(rsmd.getColumnName(col + 1)); 
    } 

    while (rs.next()) { 
     Object[] value = new Object[rsmd.getColumnCount()]; 
     for (int col = 0; col < rsmd.getColumnCount(); col++) { 
      value[col] = rs.getObject(col + 1); 
     } 
     aModel.addRow(value); 
    } 
} catch (SQLException ex) { 
    Logger.getLogger(RegisterGUI.class.getName()).log(Level.SEVERE, null, ex); 
} 
jTable2.setModel(model); 

現在,我要建一個(或表名)並返回一個TableModel

+0

非常感謝你 – Pragadees

+0

我得到一個錯誤java.sql.SQLException:[Microsoft] [ODBC Driver Manager]無效的描述符索引 – Pragadees

+0

嘗試更新... – MadProgrammer