2012-02-21 27 views
0

我試圖檢索數據庫中的表的列表並將它們存儲在Vector中。然後我希望遍歷Vector。如果Button動作命令匹配其中一個元素(即actioncommand = dbTable),我將從代碼中其他位置的選定表中檢索數據。ActionCommand和Vector

到目前爲止,我能夠得到一張表的矢量列表。但是,當我執行我的if語句時,我沒有得到任何結果。如果有人指導我如何解決問題,我將不勝感激。謝謝。

public void actionPerformed(ActionEvent e) { 
    String actionCMD = e.getActionCommand(); 
    for (Iterator itr = allTables.iterator();itr.hasNext();){ 
     if(actionCMD.toUpperCase().equalsIgnoreCase(   
       itr.next().toString().toUpperCase())){ 
      dbTable = ationCMD; 
      break; 
     } 
    } 
} 

public void getDBTables(){ 
    try { 
      DatabaseMetaData md = conn.getMetaData(); 
      ResultSet resultset = md.getTables(null, null, "%", null); 
      this.rs = resultset; 
      allTables = new Vector(); 
      while (rs.next()) {    
       tableList = new Vector(); 
       tableList.addElement(rs.getString(3)); 
       allTables.addElement(tableList); 
      }// end while 
    } catch (SQLException ex) { 
      Logger.getLogger(TableModel.class.getName()).log(Level.SEVERE, null, ex); 
    } finally{ 
     if (rs != null) { 
      try { 
       rs.close(); 
      } catch (SQLException ex) { 
       Logger.getLogger(Menu.class.getName()).log(Level.SEVERE, null, ex); 
      } 
     } 
    } 
} 

回答

0

你加入Vector年代到allTables矢量(而不是直接添加String的),因此它將永諾失敗的比較。消除tableList

0

除非您有特定的目的(多線程同步),並且Iterator構造也不是必需的(但仍然可以使用),否則您確實不應該在新代碼中使用Vector。您還打電話給toUpperCase,但也叫equalsIgnoreCase

這就是說,因爲它是通過itr.next()Vector然後調用toString()就可以了。這永遠不會匹配。您需要遍歷Vector中的String。你還需要一種方法來擺脫外環的,一旦你匹配

boolean found = false; 
for (Iterator itr = allTables.iterator();itr.hasNext() && !found;) { 
    Vector v = itr.next(); 
    for (Iterator itr2 = v.iterator(); itr2.hasNext() && !found;) {  
     if(actionCMD.equalsIgnoreCase(itr2.next().toString())) { 
      dbTable = ationCMD; 
      found = true; 
     } 
    } 
} 

現代的方法來完成,這將是使用一個ArrayList<ArrayList<String>>

List<List<String>> allTables; 
... 
allTables = new ArrayList<ArrayList<String>>(); 
... 
tableList = new ArrayList<String>(); 

而且你的循環如下所示:

for (List<String> tables : allTables) 
{ 
    for (String s : tables) 
    { 
     if (actionCMD.equalsIgnoreCase(s)) // Why up-case? You're ignoring case 
     { 
      dbTable = ationCMD; 
      found = true; 
      break; 
     } 
    } 
    if (found) 
     break; 
} 

你也可以仍與這裏的迭代器去消除if (found)聲明,或使用List.get(index)方法來達到同樣的結果,使用計數器。恕我直言,上述只是更容易閱讀。

+0

非常感謝您的快速回復。我很高興地說,stackoverflow是我找到有關java的答案的主要資源。你解決了我的問題。我使用ArrayList。有一個問題仍然存在,那就是當我在短時間內幾次點擊按鈕時,我得到這個錯誤「來自服務器的消息:」儘管在每個事件之後關閉連接,但連接「太多」! – arjang27 2012-02-21 02:12:35

+0

@ arjang27 - 你在上面的代碼中關閉了你的結果集,但是那個錯誤是在討論與db本身的連接。我不知道你打開連接的位置('conn'對象),但是聽起來好像你在多次關閉連接而沒有關閉連接。 – 2012-02-21 02:24:09