【问题标题】:No suitable driver found for jdbc:postgresql://localhost:5432/gis找不到适合 jdbc:postgresql://localhost:5432/gis 的驱动程序
【发布时间】:2020-04-04 00:15:40
【问题描述】:

过去 3 个小时我一直在尝试让我的 Java 程序与我的 Postgres 服务器交互。我无法通过错误消息“找不到适合 jdbc:postgresql://localhost:5432/gis 的驱动程序”。这是一个 Bukkit 插件,我正在使用 IntelliJ IDEA。

代码:

try
{
    //Class.forName("org.postgresql.Driver");
    c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/gis");
}
catch(Exception e)
{
        getLogger().info(e.getMessage());
}

我尝试过的事情:

  • java -cp ./path/to/postgresjdbc.jar -jar spigot-1.15.2.jar

  • 将 jdbc 文件内部直接添加到我的 jar 文件中

  • 将 jdbc 文件添加为 IntelliJ 项目中的依赖项

  • 切换到 maven,并将以下内容放入 pom.xml:

    <dependencies>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.1</version>
        </dependency>
    </dependencies>

我无法克服我发布的错误。在这一点上,它已经占据了我整个晚上。

【问题讨论】:

标签: java postgresql intellij-idea


【解决方案1】:

在开发使用 MySQL 数据库的 Bukkit/Spigot 插件时,我曾多次遇到过这个问题。 Postgres 的过程应该是相同的。

通常,当您的插件找不到 PostgresqlJDBC 驱动程序时会发生此错误。您有两种解决方法:

选项 1. 将 .jar 添加到插件的类路径:

建议您将库设置在 plugins/lib 中,因为这样您的服务器将不会尝试将库作为 Bukkit 插件加载。通过在 pom.xml 中添加此配置,将前缀 lib/ 添加到您的类路径:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
        <archive>
            <manifest>
                <addClasspath>true</addClasspath> <-- don't know if this is needed -->
                <classpathPrefix>lib/</classpathPrefix>
            </manifest>
        </archive>
    </configuration>
</plugin>

然后确保将您的 postgresjdbc.jar 放入插件文件夹中名为 lib 的文件夹中。

选项 2. 直接在 jar 中添加依赖项:

请注意,此选项会增加插件的 jar 大小。

这可以通过 Maven 的组装插件来完成:

<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
        <archive>
            <manifest>
                <mainClass>your.main.class</mainClass>
            </manifest>
        </archive>
    </configuration>
</plugin>

如果您使用 7-zip 之类的文件压缩器打开插件的 jar,那么除了插件类之外,您还应该在其中包含驱动程序类。

如果这解决了您的问题,请告诉我。

【讨论】:

  • 这已修复它。感谢您的帮助!
猜你喜欢
  • 2021-12-05
  • 2022-09-26
  • 1970-01-01
  • 2018-11-30
  • 2020-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多