JDBC Connection with MySQL

2

I'm learning to develop java and I'm trying to get ahead in my studies to understand how to make a connection to the database, but there's a problem I can not identify.

Below the error written in the log:

  

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

     

The last packet sent 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 ConexaoMySQL file, the package I describe the class that makes the connection. Just below her 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 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 controlesincronismo package that describes the program main, following 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 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 give me security.

Thank you for your collaboration.

    
asked by anonymous 28.01.2016 / 12:24

3 answers

2

I can not comment I'm still posting an answer You need to enter the IP and the name of the database in the connection string, as the friend @JeuCasulo said it's going to be something like this, it works here.

jdbc:mysql://localhost:porta/nome_banco

I recommend the caelum Java Web booklet and it is very clear. link

    
28.01.2016 / 14:02
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 PHP as a parameter, but PHP worked because it main is on 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. So just change the program to work.

    
28.01.2016 / 14:24
0

Your serverName and myDataBase are empty, so it will not point to "nowhere" so, and your mySql login and password, too, left you blank in the workbench?

    
28.01.2016 / 13:08