0

我还是 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){

            }
        }

这是显示警告的图像。

在此处输入图像描述

我在这里找到了关于取消引用空指针的很好的初学者解释。

我想也许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;
}
4

2 回答 2

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

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

于 2013-06-04T09:20:48.177 回答
1

我认为是因为conn = MySQLConnectionClass.getCurrentConnection();。你还没有初始化conn。它使用方法的返回值进行初始化。

Null从方法返回的情况可能会发生。因此,Netbeans IDE 显示警告。

还,

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

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

于 2013-06-04T10:41:42.230 回答