2009-12-17 59 views
0

我在我的數據庫類中有這種方法,我想從MySQL表中的「dateOfBirth」列中獲取一部分數據,但我不知道爲什麼list.size()是「0」,但是當我在我的代碼中使用System.out.println()時,它將只顯示sql表的第一行,儘管我有兩行!SQL和數據庫

我的方法:

public static int getBirthPercent(String i) throws SQLException { 
    Statement stmt = conn.createStatement(); 
    List<String> list = null; 
    if (i.equals("O")) { 


     ResultSet rst = stmt.executeQuery("SELECT dateOfBirth from birthtable"); 
     while (rst.next()) { 
      String s1 = rst.getString(1); 
      if (rst.wasNull()) { 
       s1 = null; 
      } 
      String s2 = s1.substring(s1.length() - 4); 
      int s3 = Integer.parseInt(s2); 
      if (list == null && s3 < 1970) { 
       list = new ArrayList<String>(); 
       list.add(s2); 

      } else { 
       list = new ArrayList<String>(0); 

      } 

     } 


    } 
    if (i.equals("N")) { 

     ResultSet rst = stmt.executeQuery("SELECT dateOfBirth from birthtable"); 
     while (rst.next()) { 
      String s1 = rst.getString(1); 
      if (rst.wasNull()) { 
       s1 = null; 
      } 
      String s2 = s1.substring(s1.length() - 4); 
      int s3 = Integer.parseInt(s2); 
      if (list == null && s3 > 2000) { 
       list = new ArrayList<String>(); 
       list.add(s2); 
       System.out.println(list); 

      } else { 
       list = new ArrayList<String>(0); 

      } 

     } 
    } 

它會返回「0」所有「如果」的情況,但的System.out.println(),顯示[2006]這是我行的列的年度之一,雖然我有兩行它必須顯示[2006,2009]。但它不!

+0

@醋,謝謝,一切順利,但我不知道如何才能使一個意義上的代碼???真的,我不知道,我只是寫一個代碼,但我不知道寫一個好的代碼的規則。[:-(] – Johanna 2009-12-17 08:14:07

+0

這可能是一個很好的開始http://www.equivalence.co。 uk/archives/101。然後拿起Robert C. Martin的Clean Code和Martin Fowler的Refactoring等書籍,這並不難。 – 2009-12-17 08:31:30

回答

1

現在試試這個代碼,並讓我們知道。乾杯。

public static int getBirthPercent(String i) throws SQLException { 

    Statement stmt = conn.createStatement(); 
    ResultSet rst = null; 
    List<String> list = new ArrayList<String>(); 
    if (i.equals("O")) { 
     rst = stmt.executeQuery("SELECT dateOfBirth from birthtable"); 
     while (rst.next()) { 
      String s1 = rst.getString(1); 
      if (s1 != null && !s1.isEmpty()) { 
       String s2 = s1.substring(s1.length() - 4); 
       int n = Integer.parseInt(s2); 
       if (n < 1970) { 
       list.add(s2);      
       } 
      } 
     } 
    } 
    if (i.equals("N")) { 
     rst = stmt.executeQuery("SELECT dateOfBirth from birthtable"); 
     while (rst.next()) { 
      String s1 = rst.getString(1); 
      if (s1 != null && !s1.isEmpty()) { 
       String s2 = s1.substring(s1.length() - 4); 
       int n = Integer.parseInt(s2); 
       if (n > 2000) { 
       list.add(s2); 
       } 
      } 
     } 
    } 

    System.out.println(list);      

    } 

現在已經夠重構了。試着爲自己做更多。例如,

  • 考慮公共朗StringUtils的更換空檢查,
  • 使用日期對象來存儲日期和使用rs.getDate()代替,
  • 您可以使用日曆對象,以獲取一年過去了。甚至SimpleDateFormat的對象將工作太
  • 等...