加载Postgresql JDBC 4.1驱动程序

时间:2014-05-09 07:09:45

标签: java postgresql maven jdbc

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

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

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

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

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

2 个答案:

答案 0 :(得分:5)

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

正确的网址是:

jdbc:postgresql://localhost:5432/database_name

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

jdbc:postgresql://localhost/database_name

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

如果该课程不可用,您将从ClassNotFoundException获得DriverManager而不是“消息”。

答案 1 :(得分:0)

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

相关问题