How to Connect to PostgreSQL with Java (JDBC) in Eclipse

In this tutorial, we will walk you through the process of downloading and setting up the PostgreSQL JDBC driver in Eclipse and connecting to a PostgreSQL database using a Java program. This step-by-step guide will help you install PostgreSQL, set up the JDBC driver, write a Java program, and test the database connection.

What You Will Learn:

  • How to download and install the PostgreSQL server.
  • Setting up a Java project in Eclipse.
  • How to download and configure the PostgreSQL JDBC Driver in Eclipse.
  • Writing a Java program to connect to PostgreSQL.
  • Running the Java program and viewing the output.

Technologies Used:

  • JDK: Version 1.8 or later (Recommended: Latest version)
  • PostgreSQL JDBC Driver: Version 42.7.4 (latest)
  • IDE: Eclipse Neon or any preferred IDE (e.g., IntelliJ IDEA)
  • JDBC: Version 4.2

Step 1: Download PostgreSQL JDBC Driver

To connect to a PostgreSQL database from your Java program, you need to download the PostgreSQL JDBC driver.

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'

If you are not using any dependency management tools (like Maven or Gradle), download the PostgreSQL JDBC driver from the official website and add the .jar file to your project classpath.

Step 2: Setting Up PostgreSQL Database

Before proceeding with the connection, ensure you have installed PostgreSQL on your system. If not, you can download and install it from the official PostgreSQL website.

Creating a New Database:

After PostgreSQL is installed, you can create a database by running the following SQL command:

CREATE DATABASE mydb;

This command creates a new database named mydb, which we will use in our Java program.

Step 3: Creating a Java Project in Eclipse

  1. Open Eclipse and create a new Java Project.
  2. Add the PostgreSQL JDBC driver to your project classpath:
    • Right-click on the project and select Build Path → Configure Build Path.
    • Click Add External JARs... and select the PostgreSQL JDBC .jar file.
    • Click Apply and Close.

Step 4: Writing a Java Program to Connect to PostgreSQL

PostgreSQL JDBC Connection String

The format for the PostgreSQL JDBC connection string is:

jdbc:postgresql://<database_host>:<port>/<database_name>
  • database_host: Hostname where PostgreSQL is running (usually localhost for local development).
  • port: The PostgreSQL port (default is 5432).
  • database_name: The name of the database (in our case, mydb).

Example Connection String:

jdbc:postgresql://localhost/mydb

Java Code to Connect to PostgreSQL

Here’s the complete Java code for connecting to the PostgreSQL database:

package net.javaguides.postgresql.tutorial;

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

public class JDBCPostgreSQLConnection {

    // 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 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) {
        JDBCPostgreSQLConnection app = new JDBCPostgreSQLConnection();
        // Connect to the PostgreSQL database
        app.connect();
    }
}

Explanation:

  • URL: The JDBC connection string jdbc:postgresql://localhost/mydb.
  • DriverManager.getConnection(): Establishes a connection to the PostgreSQL server.
  • Connection object: This object is returned by the connect() method and used to interact with the database.
  • Exception Handling: We catch and print any SQLExceptions that occur during the connection process.

Step 5: Running the Java Program in Eclipse

  1. After writing the code, save the Java file.
  2. Right-click on the Java file in Eclipse, and select Run As → Java Application.

Output:

If the connection is successful, you will see the following message in the Eclipse console:

Connected to the PostgreSQL server successfully.

If there is any issue (such as incorrect credentials or the PostgreSQL server is not running), an error message will be printed instead.

Conclusion

In this tutorial, we demonstrated how to:

  • Download and configure the PostgreSQL JDBC Driver in Eclipse.
  • Write a Java program to connect to a PostgreSQL database.
  • Successfully establish the connection and test it.

This guide provides a simple yet powerful foundation for developing applications that interact with PostgreSQL using JDBC. You can expand on this to perform CRUD operations and more complex queries in your applications.

Comments