How to connect to PostgreSQL with Java

2017. August 1.
  1. Download and start PostgreSQL from
  2. Add the postgresql dependency in your build.gradle file (compile group: 'postgresql', name: 'postgresql', version: '9.0-801.jdbc4')
  3. You are ready to connect to PostgreSQL with for example the following program:
package hello;

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

public class HelloWorld {

    private final String url = "jdbc:postgresql://localhost:5432/postgres";
    private final String username = "postgres";
    private final String password = "your-password";

    public Connection connect() {
        try {
        } catch (ClassNotFoundException e ) {
            System.out.println("Where is your PostgreSQL JDBC Driver? "
                    + "Include in your library path!");

        Connection c = null;

        try {
            c = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");

        if (c != null) {
            System.out.println("You made it, take control your database now!");
            return c;
        } else {
            System.out.println("Failed to make connection!");
            return null;

    public static void main(String[] args) {
        HelloWorld hello = new HelloWorld();

Additionally, this is how we can query the database:

ResultSet rs;

try {
	rs = st.executeQuery("SELECT * from animals");
	while ( {
		System.out.print("Column returned 1:");
} catch (SQLException e ) {
	System.out.println("Resultset creation failed!");

Hi, I'm Gábor. I am a web developer and improv comedian. You can book my workshop, read my posts,download my free ebook, buy my not-so-free ebook or try out my app.

. No spam. Unsubscribe anytime.