0

I am trying to connect to my Postgresql database but when trying to connect to the driver I get an error message saying 'unable to load driver class!'. I don't understand why this is happening. Is there anything I've missed in the code I've written?

public class getDatabase {

private Connection conn;
private PreparedStatement getEmployees;


public getDatabase() {

    try {
        Class.forName("org.postgresql.Driver"); 
        conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "anna123");
    }
    catch(ClassNotFoundException ex) {
            System.out.println("Error: unable to load driver class!");
            System.exit(1);
    } catch (SQLException e1) {
        e1.printStackTrace();
    } catch (Exception e2) {
        e2.printStackTrace();
    }
    //Setting up the prepared SQL-queries we will need.
    try {
        getEmployees = conn.prepareStatement("SELECT * FROM employee");

    } catch (SQLException e) {
        System.out.println("Error: unable to prepare SQL statements.");
        e.printStackTrace();
    }   

}
coder
  • 538
  • 7
  • 17
  • 3
    Do you have `org.postgresql.Driver` class in the classpath? – Héctor Feb 28 '18 at 16:47
  • I'm pretty sure you don't need to load the driver class yourself anymore in modern JDBC. – M. Prokhorov Feb 28 '18 at 16:48
  • Can you post the whole stacktrace instead of just your error message ? Even if I think Héctor already gave the answer : you don't have a jar containing the Driver class in your classpath. – Julien Feb 28 '18 at 16:48
  • I'm not sure.. How do you add the org.postgresql.Driver class to the classpath? @Héctor – coder Feb 28 '18 at 16:53
  • Are you using Maven or something like that? If so, you need to add Postgresql driver dependency (https://mvnrepository.com/artifact/postgresql/postgresql/9.1-901-1.jdbc4). If you are not using any build tool, you need to do it manually (command line) or using your IDE. Which one are you using? – Héctor Feb 28 '18 at 17:00
  • Just the command line and Visual Studio code. @Héctor – coder Feb 28 '18 at 17:02
  • Wow, you're brave. Then, maybe this helps you https://stackoverflow.com/questions/2096283/including-jars-in-classpath-on-commandline-javac-or-apt – Héctor Feb 28 '18 at 17:03

0 Answers0