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.
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.
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.