通过最基础的jdbc形式来连接postgresql,相关代码如下:

package com;

import java.sql.*;

public class DbTest {

	private static String url = "jdbc:postgresql://127.0.0.1:5432/test";
	private static String driver = "org.postgresql.Driver";
	private static String user = "postgres";
	private static String password = "postgres";

	public static void main(String[] args) {
		String sql = "select * from biz_account";
		DbTest dbHelper = new DbTest(sql);
		try {
			ResultSet resultSet = dbHelper.getStatement().executeQuery();
			System.out.println("Id      username        password");
			while (resultSet.next()) {
				System.out.println(resultSet.getString(1) + "          " + resultSet.getString(2) + "             " + resultSet.getString(3));
			}
			dbHelper.close();
		} catch (SQLException e) {
			dbHelper.close();
			e.printStackTrace();
		}

	}


	private Connection connection = null;

	public Connection getConnection() {
		return connection;
	}


	public PreparedStatement getStatement() {
		return statement;
	}


	private PreparedStatement statement = null;

	public DbTest(String sql) {
		try {
			Class.forName(driver);
			connection = DriverManager.getConnection(url, user, password);
			statement = connection.prepareStatement(sql);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void close() {
		try {
			this.connection.close();
			this.statement.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}


java jdbc连接postgresql插图

关注公众号:程序新视界,一个让你软实力、硬技术同步提升的平台

除非注明,否则均为程序新视界原创文章,转载必须以链接形式标明本文链接

本文链接:https://choupangxia.com/2020/07/01/java-jdbc-postgresql/