2017-05-30 42 views
-2

我讀數據庫中MySql並在ArrayList存儲的值,並將其返回錯誤的返回類型..給錯誤,在Java中

public ArrayList getData(String rule) { 
    try { 
     String q = "select distinct email_id from logs where rule ='" + rule + "';"; 
     System.out.println(q); 
     rs = st.executeQuery(q); 
     ArrayList emails = new ArrayList(); 
     while (rs.next()) { 
      emails.add(rs.getString("email_id")); 
     } 
     return emails; 

    } catch (Exception e) { 
     System.out.println("" + e); 
    } 
} 

什麼是錯的這一段代碼。它給出了一個錯誤,「它必須返回ArrayList類型的結果」..但我回來的類型只有ArrayList類型的'電子郵件'..幫我找出這個錯誤..

+0

提示:如果發生異常會發生什麼?在這種情況下應該做什麼程序?這不是在這種情況下返回。檢查所有可能的代碼執行流程。 –

+1

作爲旁註:[GENERICS](https://docs.oracle.com/javase/tutorial/java/generics/types.html),不要使用rawtypes .. – SomeJavaGuy

+0

您正在將它們返回到try-block ,當發生異常時你不會返回任何東西。您可以在catch塊中或僅在方法結束時返回null,具體取決於方法的目標是什麼。 – RedSonja

回答

1

而不是在你的內部創建你的數組嘗試範圍,在你的方法範圍內創建它,然後在你的程序結束時返回它,這樣你就可以使用某些東西像這樣:

public ArrayList getData(String rule) { 
    ArrayList emails = new ArrayList();//<<----create the list here 
    try { 
     String q = "select distinct email_id from logs where rule ='" + rule + "';"; 
     System.out.println(q); 
     rs = st.executeQuery(q); 
     //ArrayList emails = new ArrayList();<<--------don't create the list here 
     while (rs.next()) { 
      emails.add(rs.getString("email_id")); 
     } 
     //return emails;//<<-------don't return the result here 
    } catch (Exception e) { 
     System.out.println("" + e); 
    } 
    return emails;//<<-------return the list here 
} 

另一件事情,以避免任何語法錯誤,或SQL注入,我建議在使用PreparedStatement相反,它是更安全,更有益的,例如:

public ArrayList getData(String rule) throws SQLException { 
    ArrayList emails = new ArrayList();// 
    try (PreparedStatement pstm = connection.prepareStatement(
      "select distinct email_id from logs where rule = ?")) { 
     //NOTE: Position indexes start at 1, not 0 
     pstm.setString(1, rule); 
     ResultSet rs = pstm.executeQuery(); 
     while (rs.next()) { 
      emails.add(rs.getString("email_id")); 
     } 
    } 

    return emails; 
} 
+0

非常感謝..! –

+0

歡迎您沒問題@deepakasai –