Java PostgreSQL JDBC Connection Example

In this tutorial, we will guide you through downloading the PostgreSQL JDBC driver and connecting to a PostgreSQL database using a Java program. We will cover everything from setting up the PostgreSQL server to adding the JDBC driver, writing Java code to connect to the database, and testing the connection.

What You’ll Learn:

  • Downloading the latest PostgreSQL JDBC driver.
  • Setting up a PostgreSQL database.
  • Writing Java code to connect to the database using JDBC.
  • Testing the database connection.

Technologies Used

In this tutorial, we will be using the following technologies:

  • JDK: Version 21 (latest)
  • PostgreSQL JDBC Driver: Version 42.7.4
  • IDE: Eclipse or any other preferred IDE (e.g., IntelliJ IDEA)
  • JDBC Version: 4.2

Step 1: PostgreSQL JDBC Driver Dependency

You need the PostgreSQL JDBC driver to connect your Java program to a PostgreSQL database. You can manually download or add the driver to your project using a build tool like Maven or Gradle.

For Maven users:

Add the following dependency to your pom.xml file:

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.7.4</version>
</dependency>

For Gradle users:

Add the following line to your build.gradle file:

implementation 'org.postgresql:postgresql:42.7.4'

This will automatically download and add the PostgreSQL JDBC driver to your project.

Step 2: PostgreSQL Database Setup

Before we can connect to PostgreSQL from our Java program, you must have PostgreSQL installed on your system.

To set up a PostgreSQL database:

  1. Install PostgreSQL (if you haven't already).
  2. Open pgAdmin or any PostgreSQL client.
  3. Create a new database by running the following SQL command:
CREATE DATABASE mydb;

This will create a new database called mydb that we will use in our Java application.

Step 3: JDBC Connection to PostgreSQL Database

We need to use the JDBC connection string to connect to a PostgreSQL database in Java. The format of the connection string is as follows:

jdbc:postgresql://<database_host>:<port>/<database_name>

In most cases, you can use the default localhost as the database host and omit the port number if it’s the default PostgreSQL port 5432.

Example connection string:

jdbc:postgresql://localhost/mydb

Step 4: Writing Java Code to Connect to PostgreSQL

Now, we will create a Java program that connects to the PostgreSQL database using JDBC. We will use the DriverManager class to get a connection to the database.

Here is a complete Java example:

Java Program: Connecting to PostgreSQL

package com.example.postgresql;

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

public class PostgreSQLJDBCConnection {

    // JDBC URL, username and password of PostgreSQL server
    private final String url = "jdbc:postgresql://localhost/mydb";
    private final String user = "postgres";
    private final String password = "root";

    /**
     * Connect to the PostgreSQL database
     *
     * @return a Connection object
     */
    public Connection connect() {
        Connection conn = null;
        try {
            // Connect to the PostgreSQL database
            conn = DriverManager.getConnection(url, user, password);

            // Check if connection was successful
            if (conn != null) {
                System.out.println("Connected to the PostgreSQL server successfully.");
            } else {
                System.out.println("Failed to make connection!");
            }

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }

        return conn;
    }

    public static void main(String[] args) {
        PostgreSQLJDBCConnection app = new PostgreSQLJDBCConnection();
        // Connect to the PostgreSQL database
        app.connect();
    }
}

Explanation:

  • URL: jdbc:postgresql://localhost/mydb is the connection string to the PostgreSQL database.
  • DriverManager.getConnection(): Establishes a connection to the database.
  • Connection object: This is returned by the connect() method and used to interact with the database.

Step 5: Testing the Connection

To test the database connection, simply run the main() method in your IDE. If the connection is successful, you should see the following output:

Connected to the PostgreSQL server successfully.

If there’s an issue (such as incorrect credentials or the database server is down), an error message will be printed.

Conclusion

This tutorial showed you how to download and configure the PostgreSQL JDBC driver, set up a PostgreSQL database, and connect to it from a Java program using JDBC. This setup is useful for applications that need to interact with PostgreSQL databases.

Comments