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:
- First, connect to the SQLite database.
- Next, prepare the UPDATE statement. For the
UPDATE
statement that uses parameters, you use the question marks (?) placeholder in theSET
and WHERE clauses. - Then, instantiate an object the
PreparedStatement
class by calling the prepareStatement() method of theConnection
object. - After that, set a value for each placeholder using the set* method of the
PreparedStatement
object, for example,setString()
,setInt()
, etc. - Finally, execute the
UPDATE
statement by calling theexecuteUpdate()
method of thePreparedStatement
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.0
Code 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 ?