This tutorial will show you how to delete records from table using JDBC. We have created sample table employee and inserted sample data in it and below is the program where we are deleting row from employee table where row id =1. Once records deleted successfully from table we are executing select statement to see remaining data from table. Below is java sample code to JDBC delete records from database :

package com.javahonk;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DeleteRecordsFromTable {

	public static void main(String[] args) {
	Connection connection = null;
	Statement statement = null;
	ResultSet resultSet = null;

	try {
	    // Register JDBC Driver
	    Class.forName("com.mysql.jdbc.Driver");
	    // Open connection
	    connection = DriverManager.getConnection(
		    "jdbc:mysql://localhost:3306/javahonk", "root",
		    "admin");
	    // Create query set value and execute statement

	    String sql = "delete FROM employee where id=1";
	    statement=connection.createStatement();	    
	    statement.executeUpdate(sql);
	    
	    System.out.println("Record deleted successfully "
	    		+ "form employee table \n");
	    
	    //Now select records from table to see if data is deleted
	    sql = "SELECT * FROM employee";
	    resultSet = statement.executeQuery(sql);
	      
	    System.out.println("Remainning records: \n");
	    while (resultSet.next()) {
	    	
	    int id = resultSet.getInt("id");
		String firstName = resultSet.getString("First_Name");
		String LastName = resultSet.getString("Last_Name");
		
		System.out.println("id: "+id+" First Name : " 
		+ firstName+" Last Name : " + LastName);			

	    }	   

	} catch (Exception e) {
	    e.printStackTrace();
	} finally {
	    try {
		if (connection != null) {
		    connection.close();
		}
		if (resultSet != null) {
		    resultSet.close();
		}
	    } catch (SQLException e) {
		e.printStackTrace();
	    }
	}

 }

}

 

Output:

JDBC delete records from database

 

That’s it for JDBC delete records from database

Leave a Reply

Your email address will not be published. Required fields are marked *