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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap