Your code has some problems. First, do not mix% view logic with database logic.
Since your JOptionPane
class is this question , it have serious connection management problems. I'll fix it based on what I did on this other answer here and also :
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 will look like the one below. Note that the ConnectionFactory
field represents what your CONECTAR
class was:
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();
}
}
}
Notice how the ConnectionFactory
method has become quite lean. To do this:
-
Remember to use try-with-resources . Unless you are working with Java 6 or earlier, NEVER stop using it with validarLogin(String)
, Connection
or PreparedStatement
.
-
Remember to fill in the parameters of ResultSet
properly (with PreparedStatement
in this case.
-
The setString(1, login)
will give you the return rs.next();
or true
you want depending on whether or not there is false
. In your case, it is unnecessary to read this result.
-
% w / w% is no longer required. See more about this here .