Your code has some problems. First, don’t mix visualization logic JOptionPane
with database logic.
Considering that your class ConnectionFactory
is the of this issue, she has serious problems managing the connection. I will fix it based on what I did in this other answer here and also in that:
package dao;
import java.sql.DriverManager;
import java.sql.SQLException;
public final class ParametrosDeConexao {
private final String url;
private final String usuario;
private final String senha;
public ParametrosDeConexao(String url, String usuario, String senha) {
this.url = url;
this.usuario = usuario;
this.senha = senha;
}
public Connection conectar() throws SQLException {
return DriverManager.getConnection(url, usuario, senha);
}
}
With this, your code is like this below. Note that the field CONECTAR
represents what was his class ConnectionFactory
:
private static final ParametrosDeConexao CONECTAR =
new ParametrosDeConexao(
"jdbc:postgresql://localhost:5432/topografiaJava",
"postgres",
"1");
private static final String LOGIN_SQL =
"SELECT login FROM pessoa WHERE login = ?";
public boolean validarLogin(String login) throws SQLException {
try (
Connection c = CONECTAR.conectar();
PreparedStatement ps = c.prepareStatement(LOGIN_SQL)
) {
ps.setString(1, login);
try (ResultSet rs = st.executeQuery()) {
return rs.next();
}
}
}
Note how the method validarLogin(String)
got pretty dry. For that:
Remember to use the Try-with-Resources. Unless you’re working with Java 6 or earlier, NEVER stop using it with Connection
, PreparedStatement
or ResultSet
.
Remember to fill in the parameters of PreparedStatement
adequately (with the setString(1, login)
in this case.
The return rs.next();
will give the true
or false
that you want depending on whether or not there is result in ResultSet
. In your case, it is unnecessary to read this result.
The Class.forName
no longer needed. See more about this here.