SQLite Java: Update Data

Summary: This tutorial shows you how to update data in a table from a Java program using JDBC.

To update data in a table using JDBC from a Java program, you follow these steps:

  1. First, connect to the SQLite database.
  2. Next, prepare the UPDATE statement. For the UPDATE statement that uses parameters, you use the question marks (?) placeholder in the SET and WHERE clauses.
  3. Then, instantiate an object the PreparedStatement class by calling the prepareStatement() method of the Connection object.
  4. After that, set a value for each placeholder using the set* method of the PreparedStatement object, for example, setString(), setInt(), etc.
  5. Finally, execute the UPDATE statement by calling the executeUpdate() method of the PreparedStatement object.

The following Java program illustrates how to update the name and capacity of the warehouse with id 3:

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

public class Main {
    public static void main(String[] args) {
        var url = "jdbc:sqlite:my.db";
        var sql = "UPDATE warehouses SET name = ? , "
                + "capacity = ? "
                + "WHERE id = ?";

        var name = "Finished Products";
        var capacity = 5500;
        var id = 3;

        try (var conn = DriverManager.getConnection(url);
             var pstmt = conn.prepareStatement(sql)) {
            // set the parameters
            pstmt.setString(1, name);
            pstmt.setDouble(2, capacity);
            pstmt.setInt(3, id);
            // update
            pstmt.executeUpdate();
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        }
    }
}
Code language: Java (java)

Verify the update

The following statement retrieves the warehouse with id 3 from the warehouses table in the my.db sqlite database:

SELECT
  id,
  name,
  capacity
FROM
  warehouses
WHERE
  id = 3;Code language: SQL (Structured Query Language) (sql)

Output:

id  name               capacity
--  -----------------  --------
3   Finished Products  5500.0Code language: CSS (css)

In this tutorial, you have learned how to update data in the SQLite database from the Java program.

Was this tutorial helpful ?