Problem connecting to MySQL database using JDBC

This is how I try 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 am 100% sure that the URL, username and password are correct. I have already successfully connected to an external tool (MySQL query browser). This is the error I get:

com.mysql.jdbc.CommunicationsException: Communication communication error due to underlying exception:

** START EXCEPTION FAULT **

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

...

+5
source share
5 answers

, url. MySQL localhost, localhost 127.0.0.1 URL-.

:.

jdbc:mysql://localhost:3306/MY_DB

jdbc:mysql://127.0.0.1:3306/MY_DB

, .

+6

mysql , ? , , - mysql, , , , , .

, URL-, , , , , , , ..

+1

URL-. "jdbc: mysql:". , .

+1

Make sure you can connect to the database using the mysql administration tool, which will preempt your mysql and open the port.

0
source

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

If you are using an emulator for localhost, do not use the value localhostin the String connection, but use 10.0.2.2:

jdbc:mysql://10.0.2.2:3306/MY_DB

Hope this helps.

0
source

All Articles