我還是新來的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){
}
}
這裏是表示警告的圖像。
我找到了一個好初學者的解釋關於解引用空指針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;
}
你可以將你的代碼發佈爲純文本嗎? –
是的,我可以那樣做。 –
我很確定你的結果集是空的。首先嚐試在你的dbms中運行你的查詢。 –