JDBC - Connecting to the PostgreSQL database example

Posted on January 21, 2017


Technologies used:   JDK 1.8.0_121 | PostgreSQL 9.6.1 | Eclipse Mars.2 (4.5.2)

In this post, we will learn how to connect the PostgreSQL database via JDBC. There are five steps for connecting to database.

  • Load and register the JDBC driver (Class.forName() is not needed since JDBC 4.0)
  • Open connection to the database
  • Create a statement object to perform a query.
  • Execute the statement object and return a query resultset.
  • Close connection to the database

 

JAR dependencies

Download the PostgresSQL JDBC driver from https://jdbc.postgresql.org/download.html and add to build path of your project.

Java Program

Here  is an example to demonstrate the above steps.

JDBCExample.java

package com.boraji.tutorial.jdbc;

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

/**
 * @author imssbora
 */
public class JDBCExample {
  public static void main(String[] args) {

    String jdbcUrl = "jdbc:postgresql://localhost:5432/BORAJI";
    String username = "postgres";
    String password = "admin";

    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;

    try {
      // Step 1 - Load driver
     // Class.forName("org.postgresql.Driver"); // Class.forName() is not needed since JDBC 4.0

      // Step 2 - Open connection
      conn = DriverManager.getConnection(jdbcUrl, username, password);

      // Step 3 - Execute statement
      stmt = conn.createStatement();
      rs = stmt.executeQuery("SELECT version()");

      // Step 4 - Get result
      if (rs.next()) {
        System.out.println(rs.getString(1));
      }

    } catch (SQLException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } finally {
      try {

        // Step 5 Close connection
        if (stmt != null) {
          stmt.close();
        }
        if (rs != null) {
          rs.close();
        }
        if (conn != null) {
          conn.close();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

  }
}

Output

PostgreSQL 9.6.1, compiled by Visual C++ build 1800, 64-bit