开发者

A problem connecting to a MySQL DB using JDBC

开发者 https://www.devze.com 2023-01-31 17:58 出处:网络
Here\'s how I\'m trying to connect: try { Class.forName(\"com.mysql.jdbc.Driver\").newInstance(); } catch (Exception e) {

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 ext开发者_JS百科ernal 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

...


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.


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...


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消