PostgreSQL JDBC: Updating Data
Summary: in this tutorial, you will learn how to update data in a PostgreSQL database using JDBC API.
Steps for updating data
To update data in a table of a PostgreSQL database, you follow these steps:
- Create a database connection by instantiating a
Connection
object. - Create a
PreparedStatement
object. - Execute an UPDATE statement by calling the
executeUpdate()
method of thePreparedStatement
object. - Close the
PreparedStatement
andConnection
objects by calling theclose()
method.
Updating data example
The following defines the update()
method that changes the name
and price
of a product specified by product id:
How it works.
First, construct an UPDATE
statement that updates the name
and price
of a product by id:
Second, initialize a variable that stores the number of affected rows:
Third, establish a connection and create a PreparedStatement
object:
Fourth, bind values to the statement:
Fifth, execute the statement and assign the return value of the executeUpdate()
method to the affectedRows
variable:
Finally, return the number of affected rows:
The following shows how to use the ProductDB
class to update the name and price of the product:
Output:
Verify the update
First, open the Command Prompt on Windows or Terminal on Linux and connect to the PostgreSQL server:
Second, retrieve the product with id 1 to verify the update:
Summary
- Use a
PreparedStatement
object to update data in a table from a Java program.