Error: Could not find or load main class PostgresWithJDBCConnection

92 views Asked by At

I am trying to run a java file which tests whether my java file is well connected to postgresql@14 using JDBC(jar file) in VSCode environment. But I am facing some problems.

First, the tree visualization of my current directory(called FamilyCalendar) is as follows:

.
├── DateBox.java
├── FamilyCalendar.java
├── PostgresWithJDBCConnection.class
├── PostgresWithJDBCConnection.java
├── PostgresWithJDBCDelete.java
├── PostgresWithJDBCInsert.java
├── PostgresWithJDBCSelect.java
├── PostgresWithJDBCUpdate.java
├── StringManager.java
└── postgresql-42.6.0.jar

And the following is PostgresWithJDBCConnection.java source code.

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

public class PostgresWithJDBCConnection {
    public static void main(String[] args) {

        try (Connection connection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/dob", "dob",
                "MY_PASSWD")) {
            System.out.println("Connection established successfully");
        } catch (SQLException e) {
            System.out.print(e.getMessage());
        }
    }
}

To test the connection, I tried both ways; terminal environment and VSCode UI.

Terminal Environment

I tried the following commands.

javac -cp './postgresql-42.6.0.jar' PostgresWithJDBCConnection.java
java -cp './postgresql-42.6.0.jar' PostgresWithJDBCConnection

Then, for the second command line(java -cp ..), the error occurs;

Error: Could not find or load main class PostgresWithJDBCConnection

But as you can see my tree visualization of the working directory, there is definitely such class file.

VSCode UI

After I failed with the previous one, I just decided to click the run button(▶️) on the right-top of VSCode, but the error occurs as well:

[Running] cd "/Users/dob/Justin/FamilyCalendar/" && javac PostgresWithJDBCConnection.java && java PostgresWithJDBCConnection
No suitable driver found for jdbc:postgresql://127.0.0.1:5432/dob
[Done] exited with code=0 in 1.208 seconds

Seemingly it's because I didn't clarify the .jar file(for JDBC) - but does it mean I always have to manually clarify the path?

Can anyone explain what the problem is and let me know how to solve it?

Thanks for reading! Please let me know if my description was insufficient for you to handle the problem.

The thing is that I successfully run everything with all the environments and files the exact same in virtual machine that uses Ubuntu - this may not be that informational though.

0

There are 0 answers