JDBC SQL DELETE Query Example

In previous posts, we have learned about types of JDBC drivers and the how to make database connection using JDBC and then how to execute SELECT Query, and then INSET Query example. Let’s move forward. In this example I am picking up execution of SQL DELETE queries using JDBC.

JDBC-Icon

SQL DELETE query are executed to remove/delete data stored in relational databases. It requires following steps:

1) Make a database connection
2) Execute the SQL DELETE Query

Pr-requisites include setting up a database schema and creating a table first.

CREATE SCHEMA 'JDBCDemo' ;

CREATE TABLE 'JDBCDemo'.'EMPLOYEE'
(
	'ID' INT NOT NULL DEFAULT 0 ,
	'FIRST_NAME' VARCHAR(100) NOT NULL ,
	'LAST_NAME' VARCHAR(100) NULL ,
	'STAT_CD' TINYINT NOT NULL DEFAULT 0
);

Let’s write above steps in code:

1) Make a database connection

Though we have already learned about it in making JDBC connection, lets recap with this simple code snippet.

Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager
	.getConnection("jdbc:mysql://localhost:3306/JDBCDemo", "root", "password");

2) Execute the SQL DELETE Query

This is the main step and core part in the post. It requires creating a Statement object and then using it’s execute() method.

Statement stmt = connection.createStatement();
stmt.execute("DELETE FROM EMPLOYEE WHERE ID >= 1");

Above statement will execute delete statement in database we are connected to. This will remove all records which match by where clause.

Let’s see the whole code in working.

package com.howtodoinjava.jdbc.demo;

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

public class DeleteDataDemo {
	public static void main(String[] args) {
		Connection connection = null;
		Statement stmt = null;
		try 
		{
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/JDBCDemo", "root", "password");
			
			stmt = connection.createStatement();
			stmt.execute("DELETE FROM EMPLOYEE WHERE ID >= 1");
		} 
		catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {	
				stmt.close();
				connection.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}	
}

That’s all in this post. Drop me a comment if something needs explanation.

Happy Leaning !!

Leave a Reply

10 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial