JDBC connection to Mysql

Asked

Viewed 5,297 times

2

I’m learning how to develop java and I’m trying to advance my studies to understand how to make a database connection, but there’s some problem that I’m not able to identify.

Below the error written in the log:

com.mysql.jdbc.exceptions.jdbc4.Communicationsexception: Communications link Failure

The last Packet sent successfully to the server was 0 milliseconds ago. The driver has not Received any packets from the server.

I created a package br.com.ConexaoBanco that inside there is a file ConexaoMySQL, the package I describe the class that makes the connection. Just below the example of it.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.ConexaoBanco;

/**
 *
 * @author hotsystems
 */
import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

public class ConexaoMySQL {

    public static String status = "Não conectou...";

    public ConexaoMySQL() {

    }

    public static java.sql.Connection getConexaoMySQL() {

        Connection connection = null;          //atributo do tipo Connection

        try {

            String driverName = "com.mysql.jdbc.Driver";

            Class.forName(driverName);

            String serverName = "";    

            String mydatabase ="";       

            String url = "jdbc:mysql://" + serverName + "/" + mydatabase;

            String username = "";          

            String password = "";      

            connection = DriverManager.getConnection(url, username, password);

            //Testa sua conexão//  
            if (connection != null) {

                status = ("STATUS--->Conectado com sucesso!");

            } else {

                status = ("STATUS--->Não foi possivel realizar conexão");

            }

            return connection;

        } catch (ClassNotFoundException e) {  

            System.out.println("O driver do banco de dados nao foi encontrado.");

            return null;

        } catch (SQLException e) {

            System.out.println(e);
            System.out.println("Nao foi possivel conectar ao Banco de Dados.");

            return null;

        }

    }

    public static String statusConection() {

        return status;

    }

    public static boolean FecharConexao() {

        try {

            ConexaoMySQL.getConexaoMySQL().close();

            return true;

        } catch (SQLException e) {

            return false;

        }

    }

    public static java.sql.Connection ReiniciarConexao() {

        FecharConexao();

        return ConexaoMySQL.getConexaoMySQL();

    }

}

In the main class, I have a package controlesincronismo that I describe the main of the program, following his example.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controlesincronismo;

import br.com.ConexaoBanco.ConexaoMySQL;

/**
 *
 * @author hotsystems
 */
public class ControleSincronismo {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        ConexaoMySQL con = new ConexaoMySQL();
        con.getConexaoMySQL();
        con.statusConection();
    }

}

Error:

 com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
    at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:981)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:339)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2253)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2286)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2085)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:795)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:400)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:327)
    at java.sql.DriverManager.getConnection(DriverManager.java:571)
    at java.sql.DriverManager.getConnection(DriverManager.java:215)
    at br.com.ConexaoBanco.ConexaoMySQL.getConexaoMySQL(ConexaoMySQL.java:81)
    at controlesincronismo.ControleSincronismo.main(ControleSincronismo.java:27)
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:579)
    at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:211)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:298)
    ... 16 more

What has been my mistake ? And I would also like to know if these are the best practices to provide me security.

Thank you for your cooperation.

  • 1

    You’re putting the server port in too?

  • No, need ? Because in PHP gave only put my link in case is 127.0.0.1

  • Try putting it like this to see if it works: jdbc:mysql://hostname:port/databasename

  • @adelmo00 which is the standard port ?

  • the standard is 3306

  • made a crazy mistake, I updated the question

Show 2 more comments

3 answers

2

I can’t comment yet I’m putting an answer You need to inform the IP and the name of the database in the connection string, as the friend @Jeucasulo said will look something like this, here it works.

jdbc:mysql://localhost:porta/nome_banco

I recommend the booklet of Java Web from Caelum her and very clear. https://www.caelum.com.br/apostila-java-web/bancos-de-dados-e-jdbc/

2

I was able to identify the problem, I was actually trying to connect to a server on my machine, in my question I used as a parameter the PHP, however the PHP it worked because the main is in the machine where the server was, and for this reason it worked.

The solution was to change the 127.0.0.1 to the remote address of my machine. Then it was enough to change the program to work.

0

Your servername and myDataBase are empty, it will not direct to "nowhere" like this, and your mysql login and password too, you left blank in Workbench?

  • Friend I left empty, because I did not want to inform this information. I’m putting the same data I put in the application that is already working in PHP. So probably not this data.

  • 1

    It makes sense, sorry the inattention, I would pay attention to these strings because any detail will result in unexpected behavior, this error is currently common when mysql is not running or when the firewall is blocking the port or error address, with me was always the same address

Browser other questions tagged

You are not signed in. Login or sign up in order to post.