简体   繁体   English

Java JDBC - 找不到合适的驱动程序

[英]Java JDBC - No suitable Driver found

I've got a problem with my code accessing a local database.我的代码访问本地数据库时遇到问题。 I am using Eclipse and postgresql.我正在使用 Eclipse 和 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.驱动程序的 jar 文件已经在库中并且也被添加到构建路径中。 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无法获得连接:java.sql.SQLException:找不到适合 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.您的 JDBC URL 无效。 Try changing it to:尝试将其更改为:

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

See the PostgreSQL JDBC docs for more information.有关更多信息,请参阅PostgreSQL JDBC 文档

When you get your URL correct, please consider rethinking your class design.当你的 URL 正确时,请考虑重新考虑你的类设计。 java.sql.Statement is not thread safe. java.sql.Statement不是线程安全的。 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.您应该在方法范围内创建StatementResultSet ,使用它们,并在退出方法之前关闭它们。

You should be pooling database connections.您应该汇集数据库连接。

Database access has been solved for a long time in Java.数据库访问在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.如果您不使用 Spring Boot,我建议您查看他们的JdbcTemplate实现,以了解如何使用最少的样板来完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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