【问题标题】:Java Null pointer exception [duplicate]Java空指针异常[重复]
【发布时间】:2016-04-28 15:21:28
【问题描述】:

我们正在尝试在文本区域中显示数据库表中的信息。

public void displayEmployees() 
{     
  String sqlDisplayQuery =""; 
  sqlDisplayQuery+= "Select * from JAVAUSER.Employee";  
  System.out.println(sqlDisplayQuery); 

  Driver.sendDBCommand(sqlDisplayQuery);

  try
 { 
    while (dbResults.next())
    { 
        int employeeID= dbResults.getInt(1); 
        String employeeFName = dbResults.getString(2); 
        String employeeLName = dbResults.getString(3); 
         System.out.println("Employee " +employeeID + employeeFName +  employeeLName);
         txtaOutput.appendText("Employee" +employeeID + employeeFName + employeeLName);                  
    }

    }
    catch (SQLException e)
    { 
     System.out.println(e.toString());
    }

    }
  public static boolean isNumeric(String string)
  { 
  try 
  {
      double num = Double.parseDouble(string); 
  }
  catch(NumberFormatException e)
  {
      return false;
  }
  return true; 
  }


  public static void sendDBCommand(String sqlQuery)
{
    String URL = "jdbc:oracle:thin:@localhost:1521:XE"; 
    String userID = "javauser"; 
    String userPASS = "javapass"; 
    OracleDataSource ds; 

    try 
    { 
      ds = new OracleDataSource(); 
      ds.setURL(URL);
      dbConn= ds.getConnection(userID, userPASS); 
      commStmt = dbConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      dbResults= commStmt.executeQuery(sqlQuery); 
    }
    catch (SQLException e)
    { 
        System.out.println(e.toString());
   }
}

我们在 try 语句的 while 循环中得到一个空指针异常。 SQL 没有任何错误。任何帮助将不胜感激

【问题讨论】:

  • 你在哪里设置dbResults
  • 这是我的 sendDBcommand 方法
  • dbResults 在其值被设置之前被访问。看看你的方法被调用的顺序。
  • 不要忽略 sendDBCommand 方法中的异常,它稍后会咬你。

标签: java javafx nullpointerexception try-catch resultset


【解决方案1】:

看起来dbResults 字段在Driver 类上是静态的——这可能会导致多线程出现严重问题,并且没有利用正确的面向对象——但这超出了我猜的问题范围。

看循环:

    int employeeID= dbResults.getInt(1); 

这很好,即使getInt() 不会抛出 NPE,您可能希望使用ResultSet.wasNull() 检查该值是否为 SQL 空值。

    String employeeFName = dbResults.getString(2); 
    String employeeLName = dbResults.getString(3); 

这些可以为空,但也不会抛出 NPE。

    System.out.println("Employee " +employeeID + employeeFName +  employeeLName);
    txtaOutput.appendText("Employee" +employeeID + employeeFName + employeeLName);

在这里,在这两行中,您连接了可能为 null 的字符串,因此这两个是 NullPointerExceptions 的潜在来源。我只是想知道您的堆栈跟踪中是否有行号可以帮助确定确切位置...?

如果您想检查什么可以/不能从 SQL ResultSet 返回 null,请检查 this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 2014-02-04
    相关资源
    最近更新 更多