开始学习 JDBC 并遇到了这个问题:我在 IntellijIDEA 中编写了一个简单的程序,试图连接到 Postgresql 数据库。当我从 ideshki 运行程序时,一切正常,但是当我已经构建项目并尝试运行它时,出现错误。请告诉我,可能是什么问题?项目中java版本是1.8 启动后弹出Exception说连接失败
编码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Solution {
public Connection connection(String database) {
Connection connection = null;
String url = "jdbc:postgresql://localhost/" + database.trim();
String user = "postgres";
String pass = "postgres";
try {
connection = DriverManager.getConnection(url, user, pass);
System.out.println("Connected to " + database + " database.");
} catch (SQLException e) {
System.out.println("ERROR: not connected to database.");
}
return connection;
}
public static void main(String[] args) {
System.out.println("Hello World");
Solution solution = new Solution();
solution.connection("gregs_list");
}
}
maven pom:
<?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>test</groupId>
<artifactId>test</artifactId>
<version>0.1</version>
<packaging>jar</packaging>
<!-- Зависимости -->
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<!-- PostgreSQL -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.9</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<mainClass>Solution</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
(这个问题与主要部分无关:是否有可能从某个地方获得高于 8 的 jre?除了 oracle,因为需要一个帐户,并且可能需要付款。或者您可以以某种方式运行一个为 11 或更高版本编写的项目使用 jre 8?)
您需要下载Postgresql JDBC库并将其放入 c:\program files\java\jre\lib\ext