PostgreSQL Tutorial

  • Home
  • Administration
  • Views
  • Triggers
  • Stored Procedures
  • Interfaces
    • PostgreSQL PHP
    • PostgreSQL Python
    • PostgreSQL JDBC
Home / PostgreSQL JDBC / The Ultimate Guide to Query Data from The PostgreSQL Using JDBC

The Ultimate Guide to Query Data from The PostgreSQL Using JDBC

Summary: in this tutorial,  you will learn how to query data from a table in the PostgreSQL database using JDBC API.

To query data from a table using JDBC, you use the following steps:

  1. Establish a database connection to the PostgreSQL server.
  2. Create an instance of the Statement object
  3. Execute a statement to get a ResultSet object
  4. Process the ResultSet object.
  5. Close the database connection.

Establishing a database connection

To connect to the PostgreSQL database, you need to provide account information such as username, password, and the connection string. See the connecting to the PostgreSQL database server for more information.

For example, the following method connects to a PostgreSQL database and returns a Connection object:

1
2
3
4
5
6
7
8
9
    /**
     * Connect to the PostgreSQL database
     *
     * @return a Connection object
     * @throws java.sql.SQLException
     */
    public Connection connect() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }

The URL, user, and password are as follows:

1
2
3
    private final String url = "jdbc:postgresql://localhost/dvdrental";
    private final String user = "postgres";
    private final String password = "postgres";

Creating a Statement Object

A Statement object represents an SQL statement. First, you create a Statement object from the Connection object. Then, you execute the Statement object to get a ResultSet object that represents a database result set.

JDBC provides you with three kinds of Statement objects:

  • Statement: you use the Statement to implement a simple SQL statement that has no parameters.
  • PreparedStatement: is the subclass of the Statement class. It gives you the ability to add the parameters to the SQL statements.
  • CallableStatement: extends the PreparedStatement class used to execute a stored procedure that may have parameters.

Executing the query

To execute a query, you use one of the following methods of the Statement object:

  • execute: returns true if the first object of the query is a ResultSet object. You can get the ResultSet by calling the method getResultSet.
  • executeQuery: returns only one ResultSet object.
  • executeUpdate: returns the number of rows affected by the statement. You use this method for the INSERT, DELETE, or UPDATE statement.

Processing the ResultSet Object

After having a ResultSet object, you use a cursor to loop through the result set by calling the methods of the ResultSet object.

Note that this cursor is a Java cursor, not the database cursor.

Closing a database connection

In JDBC 4.1, you use a try-with-resources statement to close ResultSet, Statement, and Connection objects automatically.

Querying data examples

In the following section, we will show you various example of querying data from simple to complex.

Querying data with a statement that returns one row

The following method returns the number of actors in the actor table using the COUNT function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    /**
     * Get actors count
     * @return
     */
    public int getActorCount() {
        String SQL = "SELECT count(*) FROM actor";
        int count = 0;
 
        try (Connection conn = connect();
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(SQL)) {
            rs.next();
            count = rs.getInt(1);
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
 
        return count;
    }

We have done the following in the getActorCount method:

  1. First, prepared an SQL statement that counts the number of rows in the actor table.
  2. Second, established a connection to the database, created a Statement object, and executed the query.
  3. Third, processed the result set by moving the cursor the first row and get its value using the getInt() method.

The following demonstrates the output of the method.

postgresql jdbc select count

Querying data using a statement that returns multiple rows

The following getActors method queries data from the actor table and displays the actor information.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
     * Get all rows in the actor table
     */
    public void getActors() {
 
        String SQL = "SELECT actor_id,first_name, last_name FROM actor";
 
        try (Connection conn = connect();
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(SQL)) {
            // display actor information
            displayActor(rs);
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
    }

In the displayActor method, we loop through the result set and print out the information for each row.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
     * Display actor
     *
     * @param rs
     * @throws SQLException
     */
    private void displayActor(ResultSet rs) throws SQLException {
        while (rs.next()) {
            System.out.println(rs.getString("actor_id") + "\t"
                    + rs.getString("first_name") + "\t"
                    + rs.getString("last_name"));
 
        }
    }

postgresql jdbc select example

Querying data using a statement that has parameters

To query the database with parameters, you use the PreparedStatement object.

First, you use the question mark (?) as the placeholder in the SQL statement. Then, you use methods of the PreparedStatement object such as setInt, setString,… to pass the value to the placeholders.

The following method allows you to find an actor by his/her id.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    /**
     * Find actor by his/her ID
     *
     * @param actorID
     */
    public void findActorByID(int actorID) {
        String SQL = "SELECT actor_id,first_name,last_name "
                + "FROM actor "
                + "WHERE actor_id = ?";
 
        try (Connection conn = connect();
                PreparedStatement pstmt = conn.prepareStatement(SQL)) {
 
            pstmt.setInt(1, actorID);
            ResultSet rs = pstmt.executeQuery();
            displayActor(rs);
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
    }

postgresql jdbc select with parameters

You can download the full source code of the tutorial below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package com.postgresqltutorial;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
/**
*
* @author postgresqltutorial.com
*/
public class Main {
 
    private final String url = "jdbc:postgresql://localhost/dvdrental";
    private final String user = "postgres";
    private final String password = "postgres";
 
    /**
     * Connect to the PostgreSQL database
     *
     * @return a Connection object
     * @throws java.sql.SQLException
     */
    public Connection connect() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }
 
 
    /**
     * Get all rows in the actor table
     */
    public void getActors() {
 
        String SQL = "SELECT actor_id,first_name, last_name FROM actor";
 
        try (Connection conn = connect();
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(SQL)) {
            // display actor information
            displayActor(rs);
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
    }
 
    /**
     * Get actors count
     * @return
     */
    public int getActorCount() {
        String SQL = "SELECT count(*) FROM actor";
        int count = 0;
 
        try (Connection conn = connect();
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(SQL)) {
            rs.next();
            count = rs.getInt(1);
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
 
        return count;
    }
 
    /**
     * Display actor
     *
     * @param rs
     * @throws SQLException
     */
    private void displayActor(ResultSet rs) throws SQLException {
        while (rs.next()) {
            System.out.println(rs.getString("actor_id") + "\t"
                    + rs.getString("first_name") + "\t"
                    + rs.getString("last_name"));
 
        }
    }
 
    /**
     * Find actor by his/her ID
     *
     * @param actorID
     */
    public void findActorByID(int actorID) {
        String SQL = "SELECT actor_id,first_name,last_name "
                + "FROM actor "
                + "WHERE actor_id = ?";
 
        try (Connection conn = connect();
                PreparedStatement pstmt = conn.prepareStatement(SQL)) {
 
            pstmt.setInt(1, actorID);
            ResultSet rs = pstmt.executeQuery();
            displayActor(rs);
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
    }
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Main main = new Main();
        main.findActorByID(200);
    }
}

In this tutorial, we have shown you how to query data from the PostgreSQL database using JDBC API.

Previous Tutorial: How To Call PostgreSQL Stored Function Using JDBC
Next Tutorial: The Complete Guide to Insert Data Into a Table Using JDBC

PostgreSQL Quick Start

  • What is PostgreSQL?
  • Install PostgreSQL
  • Connect to Database
  • Download PostgreSQL Sample Database
  • Load Sample Database
  • Explore Server and Database Objects

PostgreSQL JDBC

  • Connect To PostgreSQL Database in JDBC
  • Query Data from PostgreSQL using JDBC
  • Insert Data Into a Table Using JDBC
  • Update Data in PostgreSQL Using JDBC
  • Call PostgreSQL Stored Function in JDBC
  • Delete Data From PostgreSQL Using JDBC
  • PostgreSQL JDBC Transaction

About PostgreSQL Tutorial

PostgreSQLTutorial.com is a website dedicated to developers and database administrators who are working on PostgreSQL database management system.

We constantly publish useful PostgreSQL tutorials to keep you up-to-date with the latest PostgreSQL features and technologies. All PostgreSQL tutorials are simple, easy-to-follow and practical.

Recent PostgreSQL Tutorials

  • PostgreSQL Recursive View
  • Learn PostgreSQL Recursive Query By Example
  • Creating Updatable Views Using the WITH CHECK OPTION Clause
  • PostgreSQL Upsert Using INSERT ON CONFLICT statement
  • How to Generate a Random Number in A Range
  • Using PostgreSQL ADD COLUMN to Add One or More Columns To a Table
  • PostgreSQL Character Types: CHAR, VARCHAR, and TEXT
  • Using PostgreSQL SERIAL To Create Auto-increment Column
  • PostgreSQL Boolean Data Type with Practical Examples
  • Understanding PostgreSQL Timestamp Data Types

More Tutorials

  • PostgreSQL PHP
  • PostgreSQL Python
  • PostgreSQL JDBC
  • PostgreSQL Functions
  • PostgreSQL Resources

Site Info

  • Home
  • About Us
  • Contact Us
  • Privacy Policy

Copyright © 2017 by PostgreSQL Tutorial Website. All Rights Reserved.