I keep getting an SQLException "No suitable driver found for jdbc Postgres", even though everything seems to be correct.
I've already included the "Class.forName("org.postgressql.Driver");" instruction at the beginning of my class, but it didn't fix it.
public class UsuarioDAO implements I_UsuarioDAO {
//Não é necesário a partir do JDBC 4.0
static {
try{
Class.forName("org.postgressql.Driver");
} catch (ClassNotFoundException e){
e.printStackTrace();
}
}
public Usuario autenticar(String login, String senha){
try(Connection c = DriverManager.getConnection("jdbc:postgresql://localhost/coursera","postgres",password)){
String query = "SELECT * FROM usuario WHERE login = ?";
PreparedStatement stm = c.prepareStatement(query);
stm.setString(1, login);
ResultSet rs = stm.executeQuery();
if(rs.next()&& rs.getString("senha").equals(senha)){
Usuario u = new Usuario(rs.getString("login"));
u.setNome(rs.getString("nome"));
u.setEmail(rs.getString("email"));
u.setSenha(rs.getString("senha"));
u.setPontos(rs.getInt("pontos"));
return u;
}
return null;
}catch (SQLException e){
throw new RuntimeException("Não foi possível executar o acesso", e);
}
}
It all seems weird, since when I try to stablish a connection to Postgres by using the "Services" tab on Netbeans, it all works fine.
Edit: It turns out that the answer to my problem lied in registering the driver before stablishing the connection.
By changing from this :
public Usuario autenticar(String login, String senha){
try(Connection c = DriverManager.getConnection("jdbc:postgresql://localhost/coursera","postgres",password)){
String query = "SELECT * FROM usuario WHERE login = ?";
to this:
public Usuario autenticar(String login, String senha){
try{
DriverManager.registerDriver(new org.postgresql.Driver());
Connection c = DriverManager.getConnection("jdbc:postgresql://localhost/coursera","postgres",password);
String query = "SELECT * FROM usuario WHERE login = ?";
Everything started to work just fine!