PostgreSQL JDBC: Delete Data from Table
Summary: in this tutorial, you will learn how to delete data from a table in the PostgreSQL database using JDBC.
Steps for deleting data from a table in JDBC
To delete data from a Java program, you follow these steps:
- Establish a database connection to PostgreSQL.
- Create a
PreparedStatement
object. - Execute a DELETE statement.
- Close the database connection.
Deleting data example
The following example adds a delete() function to the ProductDB
class to delete a product by id:
How it works.
First, construct a DELETE statement to delete a product from the products table specified by id:
Second, open a database connection and create a PreparedStatement object:
The try-with-resources statement will automatically close the statement and connection.
Third, bind the id to the statement:
Fourth, execute the prepared statement and return the number of deleted rows:
The following shows how to use the delete() method of the ProductDB
class to delete a product with the id 1 from the database table:
Output:
Verify the deletion
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 deletion:
Output:
The result set is empty, meaning that the program deleted the product with id 1 successfully.
Summary
- Use the
PreparedStatement
to delete data from a table using JDBC.