【问题标题】:Loading the Postgresql JDBC 4.1 driver加载 Postgresql JDBC 4.1 驱动程序
【发布时间】:2014-06-26 20:05:05
【问题描述】:

我想使用 JDBC 4.1 驱动程序连接到 PostgreSQL 数据库。我在pom.xml 中声明了以下依赖项:

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>9.3-1101-jdbc41</version>
</dependency>

这会将postgresql-9.3-1101-jdbc41.jar 放入我的类路径中。我已经读过,如果驱动程序在META-INF/services/java.sql.Driver 中指定,则不再需要使用Class.forName() 加载驱动程序。 driver-jar 有这个文件,但我仍然收到以下错误:

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

我只是在测试中调用,然后使用mvn test 运行测试:

DriverManager.getConnection("jdbc:postgresql://localhost:5432");

即使我在收到错误消息之前致电Class.forName()。如何正确加载驱动程序?

【问题讨论】:

    标签: java postgresql maven jdbc


    【解决方案1】:

    您的连接 URL 无效。您必须指定一个数据库,否则驱动程序将不接受该 URL。

    正确的网址是:

    jdbc:postgresql://localhost:5432/database_name
    

    或者当你使用默认端口时:

    jdbc:postgresql://localhost/database_name
    

    消息“找不到合适的驱动程序”是由DriverManager 生成的消息,它询问所有注册的驱动程序是否接受给定的 URL。第一个说“是”的驱动程序将用于打开连接。 Postgres 驱动程序不接受 URL,因为缺少数据库并且没有其他驱动程序可以询问,DriverManager“放弃”并向您显示该错误消息。

    如果课程不可用,您将收到 ClassNotFoundException 而不是来自 DriverManager 的“消息”。

    【讨论】:

    • 有趣的是,我原以为驱动程序会“接受”带有该驱动程序支持的子协议(即:jdbc:postgresql:)的连接字符串,如果不匹配则抛出 SQLException所需的格式,另一方面,这种方式也允许替代驱动程序尝试。
    • 查看stackoverflow.com/questions/23563178/postgresql-connection-java,问题可能不是缺少数据库名称,而是主机名或端口后缺少/
    • @MarkRotteveel:很好。虽然尾随/ 表示“使用与用户同名的数据库”。因此,在“种类”末尾使用 / 也可以指定数据库。
    【解决方案2】:

    这看起来像是 Maven 正确设置类路径的问题。 看看 this ,听起来像一个类似的问题。

    【讨论】:

    • 我忘了补充一点,当我运行mvn test 时出现错误。我不是在构建项目。
    猜你喜欢
    • 1970-01-01
    • 2018-08-05
    • 2011-08-24
    • 2013-10-25
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多