0

I am new to Netbeans and I decided to use Swing Forms with Java MySQL CRUD operations I have tested in Intellij before. At this point, while applying MySQL snippet as you can see below. I got "Nullpointer Exception" for the line "rs = statement.executeQuery("SELECT * FROM cities");". I also tested whether there is any database connection establishment issues with try catch phrases using "e.getMessage()" and "e.getErrorCode()" for SQLException and ClassNotFound cases but no exception returned. I have been trying understand the reason but I am having a trouble to figure it out. I will be appreciated for any help. Thanks in advance.

private static void TestWorldTable(){
   //connection presets
   String url = "jdbc:mysql://localhost:3306/world";
   ResultSet rs = null;

   try {
      //connection establishment
      Class.forName("com.mysql.jdbc.Driver");
      Connection con = DriverManager.getConnection(url, null, null);
      Statement statement = con.createStatement();
      rs = statement.executeQuery("SELECT * FROM cities");

   }
   catch (ClassNotFoundException| SQLException ignored){}

   try {
      //record retrieval observation for CRUD
      while(rs != null && rs.next()){
         System.out.println(rs.getString("name"));
   }
   catch (SQLException ignored) {}
}

Edit: The problem has been solved. The issue is solved after creating a new library and adding mysql_connector to the classpath of that library, adding dependencies of that mysql_connector to pom.xml then changing database url to ssl and servertimezone dependent version as "jdbc:mysql://localhost:3306/< DatabaseName >?useSSL=false&serverTimezone=UTC"

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

1 Answers1

1

catch (ClassNotFoundException| SQLException ignored){}

Don't do this. You're asking java to take useful information about problems and just toss it in the toilet, and now you're on SO asking, bewildered, why your code isn't work. Do not ignore exceptions unless you really, really, really know what you are doing. The right ¯\(ツ)/¯ I dunno what to do exception handler is this:

catch (SQLException e) {
    throw new RuntimeException("uncaught", e);
}

though, even better is to just declare your methods to 'throws' whatever seems relevant, and certainly SQLException is relevant here.

So what's the problem?

When running on the command line, the MySQL jdbc driver isn't on the classpath. You don't need that Class.forName bit, by the way. java will figure it out on its own. Make sure you use the -cp option to add that jdbc driver.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • As I mentioned I already tested what you said with exception handling .I still get the exception while they are ignored. The driver classpath can be the issue. Thanks for the idea – EnCoder Senjin Nov 24 '20 at 18:15