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

public class Connect {

public static void main(String[] argv) {

    System.out.println("-------- PostgreSQL "
            + "JDBC Connection Testing ------------");

    try {

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

    } catch (ClassNotFoundException e) {

        System.out.println("Where is your PostgreSQL JDBC Driver? "
            + "postgresql-9.2-1002.jdbc4.jar");
        e.printStackTrace();
        return;

    }

    System.out.println("PostgreSQL JDBC Driver Registered!");

    Connection connection = null;

    try {

        connection = DriverManager.getConnection(
                "jdbc:postgresql://localhost:5432/postgres", "postgres",
                "postgres");

    } catch (SQLException e) {

        System.out.println("Connection Failed! Check output console");
        e.printStackTrace();
        return;

    }

    if (connection != null) {
        System.out.println("You made it, take control your database now!");
    } else {
        System.out.println("Failed to make connection!");
    }
}

}

I am trying to connect Postgres SQL database to Java via JDBC driver. I have downloaded the JDBC driver an placed it in the exact folder where this code is running. I am not able to figure out why this connection is not working. Below is the error I am getting.

   Where is your PostgreSQL JDBC Driver? postgresql-9.2-  1002.jdbc4.jar:/.classes Connect
java.lang.ClassNotFoundException: org.postgresql.Driver
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:195)
    at Connect.main(Connect.java:14) 
4
  • 1
    What error output are you getting? Commented Nov 12, 2016 at 13:17
  • 5
    an placed it in the exact folder where this code is running: that doesn't matter. It must be placed in the runtime classpath. java -cp /the/path/to/postgresql.jar:./classes Connect. Java loads classes from the classpath. Not from all the jars in the current directory. Commented Nov 12, 2016 at 13:24
  • Could you make it clear? I didn't get you where exactly to add the path. Commented Nov 12, 2016 at 16:48
  • Google "Java classpath". Commented Nov 12, 2016 at 16:55

0