0

I'm learning how to connect Java to PostgreSQL, but doing almost everything manually so I learn the basics.

Here is my code

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

class Test {

    public static void main(String[] args) {
        Connection myConnection;
        PreparedStatement stmt;
    
        try {
            myConnection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/testdb", "admin", "admin");
            stmt = myConnection.prepareStatement("SELECT * FROM table");
            ResultSet rs = stmt.executeQuery();
    
            while (rs.next()) {
                rs.getString("bird");
            }
        } catch (SQLException sqlException) {
            System.out.println(sqlException.getMessage());
        }
    }

}

My Java version is 20, and I've put postgresql-42.6.0.jar in C:\libs\.

I compiled my Test.java file with javac -cp C:\libs\postgresql-42.6.0.jar Test.java, and also tried with path between double quotes, but when I try to run Test.class with java Test I get the following error:

No suitable driver found for jdbc:postgresql://localhost:5432/testdb

  • *with `java Test`* That won't work. There's no classpath there apart from the implied current directory. You should do `java -cp .;C:\libs\postgresql-42.6.0.jar Test` – g00se May 04 '23 at 12:32
  • So I should compile *without* imported `postgresql-42.6.0.jar`, but I should run with it? – jachai.sotaro May 04 '23 at 12:40
  • That's right. Compiling *with* it would not be a problem though ;) – g00se May 04 '23 at 12:56
  • The compilation doesn't reference any of the classes of the PostgreSQL JDBC driver, so it doesn't need to be present during compilation, but they do have to be present when *running* your application (so the JDBC `DriverManager` can find them and register them). – Mark Rotteveel May 04 '23 at 13:05

0 Answers0