Java - JDBC PostgreSQL Update Example


In the previous tutorial, we have seen how to insert records into a table in a PostgreSQL database using Java. In this tutorial, you will learn how to update data in a PostgreSQL database using the JDBC API.
To update data in a table in a PostgreSQL database, you use these steps:
  • Create a database connection.
  • Create a PreparedStatement object.
  • Execute the UPDATE statement by calling the executeUpdate() method of the PreparedStatement object.
  • Close the database connection.
Check out all Java PostgreSQL examples at Java PostgreSQL Tutorial.

Technologies used

We use below technologies in this tutorial:
  • JDK - 1.8 or later
  • PostgreSQL- 42.2.9
  • IDE - Eclipse Neon
  • JDBC - 4.2

Download PostgreSQL JDBC Driver

To connect to the PostgreSQL database server from a Java program, you need to have a PostgreSQL JDBC driver. You can download the latest version of the driver on the postgresql.org website via the download page.
Add the PostgreSQL JDBC driver jar file to the project classpath.
For maven users:
<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.2.9</version>
</dependency>
For Gradle users:
// https://mvnrepository.com/artifact/org.postgresql/postgresql
compile group: 'org.postgresql', name: 'postgresql', version: '42.2.9'

PostgreSQL Database Setup

In this previous tutorial, we have inserted single or multiple rows into the PostgreSQL database using the JDBC API. In this tutorial, we are going to retrieve records from the same PostgreSQL database table.

JDBC PostgreSQL Update Example

Here is the complete Java program to update a row into the "users" table in the PostgreSQL database:
package net.javaguides.postgresql.tutorial;

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

/**
 * Update PreparedStatement JDBC Example
 * @author Ramesh Fadatare
 *
 */
public class UpdateRecordExample {

    private final String url = "jdbc:postgresql://localhost/mydb";
    private final String user = "postgres";
    private final String password = "root";

    private static final String UPDATE_USERS_SQL = "update users set name = ? where id = ?;";

    public static void main(String[] argv) throws SQLException {
        UpdateRecordExample updateStatementExample = new UpdateRecordExample();
        updateStatementExample.updateRecord();
    }

    public void updateRecord() throws SQLException {
        System.out.println(UPDATE_USERS_SQL);
        // Step 1: Establishing a Connection
        try (Connection connection = DriverManager.getConnection(url, user, password);

            // Step 2:Create a statement using connection object
            PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_USERS_SQL)) {
            preparedStatement.setString(1, "Ram");
            preparedStatement.setInt(2, 1);

            // Step 3: Execute the query or update query
            preparedStatement.executeUpdate();
        } catch (SQLException e) {

            // print SQL exception information
            printSQLException(e);
        }

        // Step 4: try-with-resource statement will auto close the connection.
    }

    public static void printSQLException(SQLException ex) {
        for (Throwable e: ex) {
            if (e instanceof SQLException) {
                e.printStackTrace(System.err);
                System.err.println("SQLState: " + ((SQLException) e).getSQLState());
                System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
                System.err.println("Message: " + e.getMessage());
                Throwable t = ex.getCause();
                while (t != null) {
                    System.out.println("Cause: " + t);
                    t = t.getCause();
                }
            }
        }
    }
}
In this tutorial, we have shown you step by step how to update data in a table using JDBC API.
Check out all Java PostgreSQL examples at Java PostgreSQL Tutorial.


Comments