0

我還是新來的Java,但我不得不說,我開始得到它的hang it,它是非常酷。無論如何,在我的Netbeans IDE中,我收到了警告Dereferencing possible null pointer。請看這裏的代碼快照。您可以看到強調空指針警告的黃線。解除引用可能的空指針警告與MySQL PrepareStatement

這裏是純文本

/* 
    * Establish Connection to MySQL 
    */ 
    Connection conn; 
    conn = MySQLConnectionClass.getCurrentConnection(); 
    if (conn == null){ 
     System.out.println("MySQL not connected!"); 
    } 

    /* 
    * get the change in price-nav/price 
    */ 
    double nav_change; 
    float first_close = 0; 
    float first_nav_close = 0; 
    float last_nav_close = 0; 
    String sym = ""; 
    try{ 
     try (PreparedStatement get_p = conn.prepareStatement("SELECT close, symbol FROM test.cef_daily_data where symbol = (select symbol from cef_nav_real_time_trading_watch_list where id = ?) order by date desc limit 6,1;")) { 
      get_p.setInt(1,id); 
      ResultSet price = get_p.executeQuery(); 
      try{ 
       price.next(); 
       first_close = price.getFloat(1); 
       sym = price.getString(2); 
       price.close(); 
      }catch (SQLException e){ 

      } 
     } 

這裏是表示警告的圖像。

enter image description here

我找到了一個好初學者的解釋關於解引用空指針here

我也許想通了PreparedStatement變量:get_p有幸成爲null的可能性,所以我試圖把後檢查,以確保get_p不是null線,但這並沒有使警告消失。

所以我不只是試圖讓這個警告消失,我也試圖瞭解問題是如何提高我的Java技能。謝謝你的幫助!

更新

問題是conn變量有幸成爲null的可能性。我加了一個return線像這樣的解決了這一問題:

/* 
* Establish Connection to MySQL 
*/ 
Connection conn; 
conn = MySQLConnectionClass.getCurrentConnection(); 
if (conn == null){ 
    System.out.println("MySQL not connected!"); 
    return; 
} 
+0

你可以將你的代碼發佈爲純文本嗎? –

+0

是的,我可以那樣做。 –

+0

我很確定你的結果集是空的。首先嚐試在你的dbms中運行你的查詢。 –

回答

2
if (conn == null){ 
    System.out.println("MySQL not connected!"); 
} 

...將只顯示消息,並繼續反正參考下面的行空指針(prepareStatement調用如下使用)。如果沒有連接,您可能需要添加return或繞過實際查詢的某種錯誤處理。

+0

是的!我在System.out.println(「MySQL not connected!」)之後加了一個'return';'這個固定了警告。非常好。 –

1

我認爲它是因爲conn = MySQLConnectionClass.getCurrentConnection();。 您尚未初始化conn。它使用方法的返回值進行初始化。

可能發生Null從該方法返回。所以,Netbeans IDE顯示警告。

此外,

if (conn == null){ 
    System.out.println("MySQL not connected!"); 
} 

已經沒有任何意義,它只是將打印在控制檯上的消息,並繼續執行下一行。