-3

We are trying to display information in a textarea from a database table.

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());
   }
}

We are getting an null pointer exception at the while loop within the try statement. The SQL does not have any errors. Any help would be appreciated

1 Answers1

0

Looks like the dbResults field is static on the Driver class - this could cause serious problems with multi-threading, and does not utilize proper object-orientation - but that's beyond the scope of the question i guess.

Looking at the loop:

    int employeeID= dbResults.getInt(1); 

This is fine-ish, even though getInt() won't throw an NPE, you might want to check if the value was SQL null with ResultSet.wasNull().

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

These can be null, but won't throw NPE either.

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

Here, in both lines, you concat strings that could be null, so these two are potential sources of NullPointerExceptions. I am just wondering if you got line numbers in your stacktrace that could help identifying the exact location...?

If you want to check what can/cannot return null from an SQL ResultSet, check this.

sfThomas
  • 1,895
  • 2
  • 18
  • 26