0

I have a mysql db running on localhost. Database name is 'iot' and table name is 'iot'. I'm trying to connect but when checking if connection is null it is. Where am I going wrong?

I have these class variables:

private Connection connection;
private String server = "localhost:8090";
private String db = "iot";
private String username = "root";
private String password = "";
private String url = "jdbc:mysql://" + server + "/" + db;

In constructor:

Class.forName("com.mysql.jdbc.Driver").newInstance();
this.connection = DriverManager.getConnection(url, username, password);

Test:

if(connection == null){
   System.out.println("null"); //prints unfortunately
}
  • I assume the "Test" section is not running on the constructor but on some method. Did you set the value of `this.connection` to null, in between (the constructor and the method)? I guess so... – The Impaler Mar 12 '19 at 19:48
  • Yes, the test is in a metod. I did not set it to null, should I? – user10990200 Mar 12 '19 at 19:50
  • Can you show the value of `connection` right after you get it -- that is in the constructor? If it's not null there, then you are setting it to null somewhere in between the constructor and the method. – The Impaler Mar 12 '19 at 19:52
  • `localhost:8090` are you sure about the port? The default port is 3306. Also, use the latest version of driver and driver class `com.mysql.cj.jdbc.Driver`. – Atul Mar 12 '19 at 19:54
  • That's weird. It's not null when checking in the constructor. I have a JFrame so there's a lot going on in the constructor. At the bottom I'm connecting to the database and then I'm trying to query the database on a button, that's where it's null. So it's not null in constructor but in the actionlistener class it is. @Atul yes, I'm sure it's on 8090. – user10990200 Mar 12 '19 at 19:56
  • Possible duplicate of [Connect Java to a MySQL database](https://stackoverflow.com/questions/2839321/connect-java-to-a-mysql-database) – Atul Mar 12 '19 at 19:57
  • Actually @Atul, you are right. lol – user10990200 Mar 12 '19 at 19:59
  • Also. with newer versions of JDK, there is no need to use `newInstance()` to load the class. – Atul Mar 12 '19 at 20:05

0 Answers0