简体   繁体   中英

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

...

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

Eg:

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.

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.

检查您是否可以从mysql管理工具连接到数据库,这将驱逐您的mysql是否正在运行以及该端口是否已打开。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM