Home > Mobile >  Postgresql 14 connection failed - No suitable driver
Postgresql 14 connection failed - No suitable driver

Time:07-18

I'm trying to resolve the common issue "How to add jdbc driver / No suitable driver found"

Postgres database installed and my other service used SpringBoot connects to database without issues:

spring:
  jpa:
    hibernate:
      ddl-auto: create
    database-platform: org.hibernate.dialect.PostgreSQLDialect
    show-sql: true
  datasource:
    url: "jdbc:postgresql://localhost:5432/garage"
    username: garage_owner
    password: XXXX

However i would like to establish connection by DriveManager

P.S. Yes, DataSource is preferable choice, it has connection pools etc :), but for experiment i need DriveManager

My PostgreSQL version is 14

C:\Users\fessu>postgres --version
postgres (PostgreSQL) 14.4

I downloaded postgresql-42.4.0 jdbc driver, and added it into Project: enter image description here

Now it's expected to be loaded:

enter image description here

This is a few line class code - i just need to establish connection:

public class JdbcMain {         
final String URL = "jdbc:postgresql://localhost:5432/garage";
    public static void main(String[] args) {
    
            new JdbcMain().setConnectionByDriverManager();
    
        }
    
    public void setConnectionByDriverManager() {
            //https://jdbc.postgresql.org/documentation/head/load.html
            //Class.forName("org.postgresql.Driver");
    
            try {
                Connection connection = DriverManager.getConnection(URL, "garage_owner", "XXXX");
                System.out.println("Connected!");
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
}

However I got well known error:

Caused by: java.sql.SQLException: No suitable driver found for jdbc:postgresql://localhost:5432/garage

Postgresql and jdbc versions are compatible, url is correct.

What did i miss in setting up jdbc manually?

CodePudding user response:

It’s a problem at runtime you experience. The driver‘s classes are not available once you execute your demo class. This originates from your project setup.

Add postgresql-42.4.0.jar as a library, instead of as module export, to the project. This way IntelliJ will provide the driver in a runtime scope for your experiments.

I see you have Gradle in the project. In such a setup, the JDBC driver could also be managed by Gradle and adding

dependencies {
    //… other dependencies
    runtimeOnly 'org.postgresql:postgresql:42.4.0'
}

to build.gradle and letting Gradle do the job.

  • Related