Java JDBC Delete a Record in Database Table using PreparedStatement

In this Tutorial, we will take a look at how to delete a database table record using Java JDBC PreparedStatement,

Table Entries before delete
mysql> select * from my_table;
| id | data  |
|  1 | Hello |
|  2 | Hi    |
|  1 | Bye   |
3 rows in set (0.00 sec)

Code Example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCCreateTableExample {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        String url ="jdbc:mysql://localhost:3306/my_uat";
        String userName="root";
        String password ="root123";
        String deleteQuery ="delete from my_table where id=?";
        Connection connection = DriverManager.getConnection(url,userName,password);
        PreparedStatement preparedStatement = connection.prepareStatement(deleteQuery);
        preparedStatement.setInt(1, 2);
        int count = preparedStatement.executeUpdate();
        if(count > 0) {
            System.out.println("Record deleted from the table...");
        } else {
            System.out.println("Error occurred while detecting the record from the table..");
Output: Record deleted from the table...

The table now has only two entries:

Delete record from Database table using Java JDBC PreparedStatement

Have Questions? Post them here!
Try Out Code2care Dev Tools:


Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.