How do I connect a database in a JAVA application

3

I have a Java application and a MySQL database connected to this application on my machine. The application will be distributed to other machines on the same network, but I can not make the banco de dados connection to other machines. The connection works fine locally, however, when I try to run the application on another machine on the same network, the connection fails. In MySQL I can access the database remotely. This is the connection code in the Java application (I am using NetBeans ).

    String connectionUrl = "jdbc:mysql://NOMEDOSERVER:3306/DB";
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    con = DriverManager.getConnection(connectionUrl, "root", "SENHA");
    
asked by anonymous 03.06.2015 / 16:39

2 answers

1

The only thing wrong with your code is the unnecessary call to newInstance() (just use Class.forName("com.mysql.jdbc.Driver"); only). Otherwise there is nothing wrong with your code.

Are you sure that other machines can see the database server with the given name? To test this use ping. Also, make sure there are no restrictions due to firewalls, ACLs, and network routing.

    
03.06.2015 / 16:48
1

Sincerely, this code that you put can not understand anything about the problem you are experiencing, better abstract your doubts when you ask a question.

But anyway,

I do not know how familiar you are with JDBC but this is a class that makes a connection to the mysql database, which is your case. Remember that you need a connection jar too ... again I do not know what problem you are experiencing so develop it.

Class ofConnection:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class FabricaDeConexao {
  private static final String user = "root";
  private static final String password = "SENHA";
  private static final String url = "jdbc:mysql://localhost:3306/DB";
  private static Connection con = null;

  public static Connection getConexao() {

      try {

          Class.forName("com.mysql.jdbc.Driver");
          con = DriverManager.getConnection(url, user, password);
          return con;

      } catch (Exception e) {
          System.out.println(e.getMessage());
          return null;
      }
  }

  public static void fechar() throws SQLException {
      if (con != null) {
          con.close();

      }
  }

}

Test class:

import java.sql.Connection;
import java.sql.SQLException;


public class TestaConexao {
  public static void main(String[] args) throws SQLException {
      Connection conexao = new FabricaDeConexao().getConexao();
      System.out.println("Conexão aberta!");
      conexao.close();

  }

}
    
03.06.2015 / 17:12