Java - How do I leave the Permanent Connection IP with PostGreSQL?

-1

Good morning,

Every time my machine connects to the internet, its IP changes. My question is ... How do I always get access to PostGreSQL even though the IP of my machine changes?

public class ConectarDB {

private static Connection con = null;

public static Connection getConexao() {

// Drive do PostGreSQL
    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException ex) {
       ex.printStackTrace();
       return null;
    }

// Variáveis de Conexão
    String drive    = "jdbc:postgresql";                // Drive do PostGreSQL
    String ip       = "localhost";                      // IP de Conexão ao Servidor
    String port     = "5432";                           // Porta do PostGreSQL
    String db       = "database_1";                     // Nome do Banco de Dados no PostGreSQL
    String user     = "postgres";                       // Nome do Usuário no PostGreSQL
    String password = "postgres";                       // Senha do Usuário no PostGreSQL
    String conexao  = drive + "://" + ip + ":" + port + "/" + db;

// Conectar-se ao Banco de Dados
    try {
       con = DriverManager.getConnection(conexao, user, password);        
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, "Não foi possível se conectar ao Banco de Dados!", "Aviso!", JOptionPane.ERROR_MESSAGE);
        ex.printStackTrace();
        return null;
    }

    // Retorno da Informação
    return con;

}

// Main
public void main(String[] args) {
    getConexao();
}
    
asked by anonymous 13.12.2015 / 15:55

1 answer

1

Normally the database server will be on its own server at web cloud , so a local connection is possible.

In case you asked here, if your desktop application is accessing your local database, localhost is correct, but in case you distribute it to other users outside of your internal network, you will need to have a web server to have a fixed / static ip.

If you want your machine to be a database server even with dynamic ip, use a service like no-ip to release a host masking your ip, and each time you make the ip change, the no-ip application updates the host with your new ip.

This is just an alternative, not very recommended for reasons.

Having a host or fixed ip, make use of the configuration in place of localhost, so everyone who has the host will access the same database.

    
13.12.2015 / 19:55