Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A problem connecting to a MySQL DB using JDBC

Here's how I'm trying to connect:

try {
   Class.forName("com.mysql.jdbc.Driver").newInstance();
   } catch (Exception e) {
      throw new DbConnectionException();
   }
   try {
      connection = DriverManager.getConnection(url,username,password);
   } catch (SQLException e) {
      e.printStackTrace();
      throw new DbConnectionException();
   }

I'm 100% sure that the url, username, password strings are correct. I've already connected successfully using an external tool (MySQL query browser). This is the error I receive:

com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:

** BEGIN NESTED EXCEPTION **

java.net.SocketException MESSAGE: java.net.ConnectException: Connection refused

...

like image 426
snakile Avatar asked Dec 20 '10 21:12

snakile


1 Answers

Possibly a url issue. If your code is pointing to MySQL localhost, try changing localhost to 127.0.0.1 on your url.

E.g.:

jdbc:mysql://localhost:3306/MY_DB

to

jdbc:mysql://127.0.0.1:3306/MY_DB

And see if this works.

like image 199
Buhake Sindi Avatar answered Sep 25 '22 23:09

Buhake Sindi