Class 未找到异常 Postgresql。 pom中已经导入maven依赖

Class Not Found Exception Postgresql. Already imported maven dependency in pom

错误是:java: unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown 并发生在:Class.forName("org.postgresql.Driver");

大多数时候,这是奇怪的 maven 格式化之类的,但我认为我做对了(复制粘贴)。 这里是 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>Database-Test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <build>
        <plugins>
            <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>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.4-1203-jdbc4</version>
        </dependency>
    </dependencies>
</project>

如果需要,这里是文件路径

和主要 class

import java.net.URI;
import java.net.URISyntaxException;
import java.sql.*;

public class DBTEST{
    public static void main (String[]args) throws SQLException, URISyntaxException{
        System.out.println(getConnection());
    }
    private static Connection getConnection() throws URISyntaxException, SQLException{
        Class.forName("org.postgresql.Driver");
        //String dbUrl = System.getenv("DATABASE_URL");
        String dbUrl = "postgres://fxeymwfokhsimv:bd5c9975533c20ed3ab4df7c0ea263911207854c2cac46983fafce18689a1161@ec2-184-72-162-198.compute-1.amazonaws.com:5432/dlfvrduvj5qcr";
        return DriverManager.getConnection(dbUrl);
    }
}

DB 主机和数据库 不要担心我会分享我的数据库凭据 - 这是一个测试项目,只是为了让我弄清楚如何使用它。

Maven默认不会用jar打包依赖,需要用plugin来打包。 检查此线程 - Including dependencies in a jar with Maven

您不需要 Class.forName,因为您使用的是 jdbc 4 驱动程序。 您的程序中的错误是由于未处理 ClassNotFoundException 使用 Class.forName 和无效驱动程序 URL.