-4

I am new so bear with me. But I am getting a NullPointerException somewhere in here. Any ideas? Thanks!

private  void loadInstructors()
{
  // get all account numbers from database
  try 
  {
    //myResultSet = myStatement.executeQuery( "SELECT DISTINCT lastname FROM InstEval" );
    myResultSet = myStatement.executeQuery( "SELECT DISTINCT TEAMNAME FROM APP.TEAMEVAL" );
    // add account numbers to accountNumberJComboBox
    while ( myResultSet.next() )
    {
      //instructorComboBox.addItem( myResultSet.getString( "lastname" ) );
      TeamsComboBox.addItem( myResultSet.getString( "TEAMNAME" ) );
    }
    myResultSet.close(); // close myResultSet
  } // end try
  catch ( SQLException exception )
  {
    exception.printStackTrace();
  }
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189

1 Answers1

1

Here is one way to do what you seem to want; note, I've attempted to generalize a few things here. Firstly, you should use descriptive method names (if you want team names, mention team names). Secondly, you should return appropriate types (and you're doing a distinct query) so we should return a Set - I picked a sorted set, but that's not in anyway mandatory. Next, I chose to pass the Connection object into the method. It's a good idea to close resources in the block that opens them, and thusly I only close the PreparedStatement and ResultSet objects. Finally, if you don't keep your comments updated with your code they are worse then useless.

// I think sorting the team names is good idea, and they're distinct...
private SortedSet<String> getTeamNames(Connection conn) {
  // Let's use a Set!
  SortedSet<String> teamNames = new TreeSet<String>();
  // get all team names from database, at least store the query in a local 
  // String variable. You should probably extract it to a properties file.
  final String query = "SELECT DISTINCT TEAMNAME FROM APP.TEAMEVAL";
  PreparedStatement ps = null;
  ResultSet rs = null;
  try {
    ps = conn.prepareStatement(query);
    rs = ps.executeQuery();
    // add team names to teamNames
    while (rs.next()) {
      teamNames.add(rs.getString("TEAMNAME"));
    }
  } catch (SQLException e) {
    e.printStackTrace();
  } finally {
    if (rs != null) {
      try {
        rs.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
    if (ps != null) {
      try {
        ps.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }
  return teamNames;
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249