简体   繁体   中英

No suitable driver found for jdbc:postgresql but I have install driver

I want to connect to my database so I have created this class to connect

public class DBConnection {
    private final String url = "jdbc:postgresql://localhost:5433/Litopia";
    private final String user = "postgres";
    private final String password = "postgres";

    public Connection connect() {

        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, user, password);
            System.out.println("[LitopiaServices] Connected to the PostgreSQL");
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }

        return conn;
    }
}

and because I use maven in my pom.xml I have add this:

<dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.14</version>
</dependency>

but when I run my code like that

DBConnection db = new DBConnection();
db.connect();

I have the No suitable driver found exception for jdbc:postgresql... But as you see I have install my driver and my connection class as the same code as the doc example. So I really don't understood what going on.

So my problem come from the class name that don't be fined so to solve it I have add before my connection:

Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(url, user, password);

And it works !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM