1

I'm just trying to connect to postgres (13.0.1) from java (11.0.8) on Debian 10 and get the error below:

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

public class cli_test {
    public static void main(String[] args) {
    
        try {
            Connection connection = null;
            Class.forName("org.postgresql.Driver");
            
            connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/myproj", "postgres", "<pwd>");
            
            System.out.println("Connection established successfully");
        } catch (Exception e) {
            System.out.print("error: \n" + e.toString() + "\n" + e.getMessage());
        }
    }
}

I run these commands:

CLASSPATH=/usr/lib/jvm/java-11-openjdk-amd64/lib/postgresql-42.2.18.jar
javac -verbose cli_test.java
java cli_test

I have verified that the jar file exists in that location and is set to 755 permissions.

I get this error:

java.lang.ClassNotFoundException: org.postgresql.Driver

I have spent hours searching online and found many others with this problem. No other solutions I found have fixed it. I'm trying to do this without a java ide, just a text editor.

2
  • You must add postgres jdbc driver file in your jar file. You can do that by using maven, or manually. Commented Oct 22, 2020 at 20:38
  • Also, always close directly opened connection to prevent connection leak on your database. Commented Oct 22, 2020 at 20:40

1 Answer 1

1

That's not a Java problem but you use bash in a wrong way. Setting CLASSPATH=.. will not make this environment variable available to java in the program call afterwards. Try

export CLASSPATH=.:/usr/lib/jvm/java-11-openjdk-amd64/lib/postgresql-42.2.18.jar
javac -verbose cli_test.java
java cli_test

or

CLASSPATH=.:/usr/lib/jvm/java-11-openjdk-amd64/lib/postgresql-42.2.18.jar java cli_test
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.