Falling in catch while trying to establish a connection

Asked

Viewed 47 times

1

I’m using Netbeans and can’t establish a connection. I added . postgre jar (postgresql-42.2.5.jar) in the lib folder and tested the connection in the Netbeans tab (Service > database), ok worked. but I keep falling in the catch block Follows the code:

package teste.de.conexão;

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

public class ConexaoJDBC {

    String caminho = "jdbc:postgresql://localhost:5432/postgres";
    String user = "postgres";
    String password = "postgres";

    public Connection getConnection() throws SQLException{      
        Connection con = null;
        con = DriverManager.getConnection(caminho, user, password);
        System.out.println("Conexão aberta com sucesso!! :)");
        return con;

    }

Class co main method:

package teste.de.conexão;

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

public class TesteDeConexão {

    public static void main(String[] args) {
        ConexaoJDBC JDBC = new ConexaoJDBC();
        try {
            Connection conexao = JDBC.getConnection();
            if(conexao != null){
                System.out.println("Existe uma conexao");
                conexao.close();
            }
        } catch (SQLException ex){
            System.out.println("Erro"); 
            ex.getMessage();
        }

    }

Exit:

    Erro
BUILD SUCCESSFUL (total time: 1 second)

Why do I keep falling in the catch? I should add something else for Netbeans to find the . postgres jar?

  • 1

    Do me a favor? Where it says System.out.println("Erro"); modify by System.out.println("Erro: " + ex.getMessage()); and display the error message.

  • 1

    It was a problem with the authentication password, I also noticed that I was not printing the return of ex.getMessage(), so it was not displayed on the output. Thank you

1 answer

1

Good Morning,

Add the line to your connection class.

Class.forName("org.postgresql.Driver");

This way it can identify which driver should be used for this connection.

  • Class.forName(); it was not necessary, I was able to establish the connection without this line

  • 1

    Cool!!! What you did to solve the problem?

  • 1

    I was not printing getMessage() from Exception, when I did, it warned me of the error in the bank password

Browser other questions tagged

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