snakile
snakile

Reputation: 54541

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

...

Upvotes: 5

Views: 4734

Answers (5)

Gerrlt
Gerrlt

Reputation: 39

In my case the problem was that I was using a connection from emulator to localhost.

If you use emulator to localhost don't use localhost value in connection String but use 10.0.2.2 instead:

jdbc:mysql://10.0.2.2:3306/MY_DB

Hope this helps.

Upvotes: 0

Michael Wiles
Michael Wiles

Reputation: 21194

Check that you can connect to the database from the mysql admin tool, that will drive out whether your mysql is running and that the port is open.

Upvotes: 0

Buhake Sindi
Buhake Sindi

Reputation: 89189

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.

Upvotes: 7

jzd
jzd

Reputation: 23639

Double check the format of your url. It should start with "jdbc:mysql:". Make sure you are using a current version for the driver as well.

Upvotes: 1

hvgotcodes
hvgotcodes

Reputation: 120308

did you run the mysql browser from the same machine where the code is running? What I am getting at is the permissions in mysql can be host-specific, and depending on how you set them up you might not be able to connect from the machine where the code is running.

Also, you might want to double check the url, name, pword again, perhaps with log statements or a debugger to make sure there are no typos, trailing whitespaces, etc...

Upvotes: 1

Related Questions