Javaexercise.com

Updated On 2022-03-22 00:40:50

How to Connect Java Application to PostgreSQL

To connect a Java application with a PostgreSQL database, We must have PostgreSQL JDBC Driver. It is a JAR file that contains all the supported classes and methods to perform database-related operations. You can download this from the official site (Download PostgreSQL Driver). Place this JAR file into your project directory and refer to the code.

Example: How To Connect Java To PostgreSQL?

This is a JDBC connection where, we passed the PostgreSQL connection string that includes Database name(company), username, and password to establish a successful connection. It returns a connection object if the connection is successful. 

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

public class JavaPostgresConnectivity {

	public static void main(String[] args) {

		try (Connection conn = DriverManager.getConnection(
				"jdbc:postgresql://127.0.0.1:5432/company", "db-username", "db-password")) {

			if (conn != null) {
				System.out.println("Successfuly connected to PostgreSQL");
			} else {
				System.out.println("Connection Failed!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

After successful connectivity. It shows "Successfully connected to PostgreSQL" message to the console.

 

How to Read/Fetch Data from PostgreSQL using Java Application?

In the above example, we created an example to connect Java application, now, we will read the data from a table(employee) that contains columns: id, name, age, and salary. After successful connection, it returns all rows of the table.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class JavaPostgresConnectivity {

	public static void main(String[] args) {

		try (Connection conn = DriverManager.getConnection(
				"jdbc:postgresql://127.0.0.1:5432/company", "db-username", "db-password")) {

			if (conn != null) {
				System.out.println("Successfuly connected to PostgreSQL");
			} else {
				System.out.println("Connection Failed!");
			}

			PreparedStatement preparedStatement = conn.prepareStatement("select * from employee");
			ResultSet resultSet = preparedStatement.executeQuery();

			while (resultSet.next()) {
				System.out.println("Employee ID: "+resultSet.getLong("id"));
				System.out.println("Employee Name: "+resultSet.getString("name"));
				System.out.println("Employee Age: "+resultSet.getInt("age"));
				System.out.println("Employee Salary: "+resultSet.getDouble("salary"));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

In this article, we have learned to connect with PostgreSQL and read data from table as well. In the next article, we will see some other operations as well.