简体   繁体   中英

Java JDBC - No suitable Driver found

I've got a problem with my code accessing a local database. I am using Eclipse and postgresql.

I am well aware that there are already several posts like that but they didn't help me on my problem so that is why I am asking myself.

The jar file for the drivers is already in the library and is also added to the Build Path. However I am still getting the error from the Driver not being found.

Can't get a connection: java.sql.SQLException: No suitable driver found for psql -h localhost beleg postgres

My code looks like this:

package DB;
import java.sql.*;

public class Connections {

private Connection dbcon;
private Statement stmt;
private Statement stmt2;

Connections(String db_url, String username, String password) {
    try {
        Class.forName("org.postgresql.Driver");
        dbcon = DriverManager.getConnection(db_url, username, password);

        stmt = dbcon.createStatement();
        stmt2 = dbcon.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, 
        ResultSet.CONCUR_READ_ONLY);
    } catch (Exception e) {
        System.out.println("Can't get a connection: " + e.toString());

        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException f) {
        }

        try {
            if (stmt2 != null)
                stmt2.close();
        } catch (SQLException f) {
        }
        try {
            if (dbcon != null)
                dbcon.close();
        } catch (SQLException f) {
        }
        System.exit(0);
    }

}

使用 Add Jar 添加了 JAR,因为它位于项目的 lib 文件夹中。

Your JDBC URL is invalid. Try changing it to:

jdbc:postgresql://localhost/<database name>

See the PostgreSQL JDBC docs for more information.

When you get your URL correct, please consider rethinking your class design. java.sql.Statement is not thread safe. It should never, ever be a shared private member variable.

You should create Statement and ResultSet in method scope, use them, and close them before exiting the method.

You should be pooling database connections.

Database access has been solved for a long time in Java. If you don't use Spring Boot, I would recommend looking at their JdbcTemplate implementation to see how it could be done with minimal boilerplate.

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