Java PostgreSQL Connection Example

In this tutorial, we will show you how to use the PostgreSQL JDBC driver to connect to the PostgreSQL database server from a Java program.

Learn more about Java and PostgreSQL at

Add the PostgreSQL JDBC driver jar file to the project classpath.
For maven users:
<!-- -->
For Gradle users:
compile group: 'org.postgresql', name: 'postgresql', version: '42.2.9'
You can use the following command to create a database in PostgresSQL server:

Java Program to Connect to the PostgreSQL Database Server

package net.javaguides.postgresql.tutorial;

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

public class JDBCPostgreSQLConnection {
    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 {
            conn = DriverManager.getConnection(url, user, password);

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

        } catch (SQLException e) {

        return conn;

     * @param args the command line arguments
    public static void main(String[] args) {
        JDBCPostgreSQLConnection app = new JDBCPostgreSQLConnection();
Connected to the PostgreSQL server successfully.

So we can connect to the PostgreSQL database server successfully.


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