2016-01-23 47 views
0

目前我正在嘗試做一個ArrayList<String>其中包含我的數據庫中的房間號。因此,目前每行數據都有一個房間號碼,例如1001,1002,1003。所以我需要做的是將這些值存儲到ArrayList<String>,但問題是我不希望重複相同的房間號內。那麼當我運行一個循環來讀取數據庫中的所有數據時,我怎樣才能使ArrayList<String>沒有重複。如何有一個從MYSQL(Java)檢索計數器

目前這是我所擁有的,我相信邏輯是錯誤的。

ResultSet rs1; 
    ArrayList<String> roomNumberList=new ArrayList<String>(); 
    try { 
     PreparedStatement statement2 = so.getPreparedStatementWithKey("SELECT room FROM et_elderly "); 
     rs1 = statement2.executeQuery(); 

     while(rs1.next()){ 
      String num=Integer.toString(rs1.getInt("room")); 
      roomNumberList.add(num); 
      if(num!=Integer.toString(rs1.getInt("room"))){ 
       roomNumberList.add(Integer.toString(rs1.getInt("room"))); 
       num=Integer.toString(rs1.getInt("room")); 
      } 
     } 

    } catch (SQLException e2) { 
     // TODO Auto-generated catch block 
     e2.printStackTrace(); 
    } 
+1

挑選不同的記錄:'選擇不同的房間從et_elderly' –

回答

0

兩種方式來解決這個問題:

  1. 更改您的SQL選擇喜歡不同的房間號碼:

    PreparedStatement statement2 = so.getPreparedStatementWithKey("SELECT DISTINCT room FROM et_elderly"); 
    
  2. 使用SET而不是List這樣的:

    Set<String> roomNumbers=new HashSet<String>(); 
    

另外,要比較字符串,請不要使用!=而要使用否定方法使用equals