使用mysql PrepareStatement取消引用可能的空指针警告

时间:2013-06-04 09:12:29

标签: java mysql jdbc nullpointerexception nullreferenceexception

我还是Java的新手,虽然我不得不说,我开始掌握它并且非常酷。无论如何,在我的Netbeans IDE中,我收到警告Dereferencing possible null pointer。请在此处查看代码的快照。您可以看到黄线突出显示空指针警告。

这是纯文本

    /*
     * 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不是{ {1}},但这并未使警告消失。

所以我不只是试图让这个警告消失,我也试图了解提高Java技能的问题。谢谢你的帮助!

更新

问题是null变量有可能是conn。我添加了这样的null行来解决问题:

return

2 个答案:

答案 0 :(得分:2)

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

...只会打印一条消息并继续引用以下行中的空指针(prepareStatement调用是以下使用它)。如果没有连接,您可能想要绕过实际查询添加return或某种错误处理。

答案 1 :(得分:1)

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

可能会从方法返回Null。因此,Netbeans IDE正在显示警告。

此外,

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

没有任何意义,它只会在控制台上打印消息并继续执行下一行。