CentOS 上 Java 连接 PostgreSQL 的示例程序

首先在 CentOS 上安装 Java 开发环境。

yum install java -y
yum install java-devel -y

安装后,检查 Java 的版本。

[root@localhost ~]# java -version
openjdk version "1.8.0_201"
OpenJDK Runtime Environment (build 1.8.0_201-b09)
OpenJDK 64-Bit Server VM (build 25.201-b09, mixed mode)

通过 Java 的版本,确定 JDK 的目录(JDK 带有 bin lib 等目录)。

[root@localhost ~]# ls /usr/lib/jvm/
java        java-1.8.0-openjdk                               java-openjdk  jre-1.8.0          jre-1.8.0-openjdk-1.8.0.201.b09-2.el7_6.x86_64
java-1.8.0  java-1.8.0-openjdk-1.8.0.201.b09-2.el7_6.x86_64  jre           jre-1.8.0-openjdk  jre-openjdk
[root@localhost ~]# ls /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.201.b09-2.el7_6.x86_64/
bin  include  jre  lib  tapset

然后,获取 JDBC 的 jar 包。

curl -O https://jdbc.postgresql.org/download/postgresql-42.2.5.jar

紧接着,设置 Java 的相关环境变量。

[root@localhost ~]# export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.201.b09-2.el7_6.x86_64
[root@localhost ~]# export CLASSPATH=.:$JAVA_HOME/jre/lib:./postgresql-42.2.5.jar
[root@localhost ~]# export PATH=$PATH:$JAVA_HOME/bin

最后,Java 连接 PostgreSQL 的示例代码(JDBCExample.java)如下所示。

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class JDBCExample {

	public static void main(String[] argv) {

		System.out.println("-------- PostgreSQL "
				+ "JDBC Connection Testing ------------");

		try {

			Class.forName("org.postgresql.Driver");

		} catch (ClassNotFoundException e) {

			System.out.println("Where is your PostgreSQL JDBC Driver? "
					+ "Include in your library path!");
			e.printStackTrace();
			return;

		}

		System.out.println("PostgreSQL JDBC Driver Registered!");

		Connection connection = null;

		try {

			connection = DriverManager.getConnection(
					"jdbc:postgresql://127.0.0.1:5432/testdb", "mkyong",
					"123456");

		} catch (SQLException e) {

			System.out.println("Connection Failed! Check output console");
			e.printStackTrace();
			return;

		}

		if (connection != null) {
			System.out.println("You made it, take control your database now!");
		} else {
			System.out.println("Failed to make connection!");
		}
	}

}

使用 javac 编译该文件,通过 java 来运行生成的 binary。

参考链接

PostgreSQL JDBC Download

CentOS中JAVA_HOME的环境变量设置- 风行天下- CSDN博客

Connect to PostgreSQL with JDBC driver – Mkyong.com

分类:PostgreSQL

Tagged as:

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google photo

You are commenting using your Google account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理