0
      public class Actor {
        String URL = "jdbc:mysql://localhost:3306/test/phone";
        String USERNAME = "root";
        String PASSWORD = "";

        Connection connection = null;
        PreparedStatement selectActors = null;
        ResultSet resultSet = null;

        public Actor(){ 
            try {
                connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);

                selectActors = connection.prepareStatement( "SELECT * FROM phone");
            } catch (SQLException e) {
                e.printStackTrace();
            } 
        }
        public ResultSet getActors() {
            try {
                resultSet = selectActors.executeQuery();
                return resultSet;
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return resultSet;
        }
    }

I'm trying to write Java code to connect to a database and display all the records in a table, but it won't work. The error I'm getting is a null pointer exception on getActors(). I've tried checking why the null pointer exception occurs but I just cannot get it. Everything else works just fine

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Where is your `Class.forName(String arg);` and what is `.../test/phone` in URL? – Naman Mar 09 '16 at 06:04
  • Thank you for pointing out `jdbc:mysql://localhost:3306/test/phone`. The error was there. Netbeans wasn't connecting to the sql database, so I created a new database within netbeans and it worked –  Mar 09 '16 at 08:14
  • But I still had to change from `ResultSet resultSet = null;` to `ResultSet resultSet;` for the null pointer exception thing to stop showing –  Mar 09 '16 at 08:17

1 Answers1

0

Replace ResultSet resultSet = null; by ResultSet resultSet; to avoid the null pointer exception.

Aziz
  • 129
  • 1
  • 9
  • Thanks, that fixed it along with some editing to the database location –  Mar 09 '16 at 08:17