HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions
  • Dark Mode

JDBC SQL DELETE Query Example

By Lokesh Gupta | Filed Under: JDBC

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 !!

TwitterFacebookLinkedinRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

10
Leave a Reply

This comment form is under antispam protection
6 Comment threads
4 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
5 Comment authors
This comment form is under antispam protection
  Subscribe  
newest oldest most voted
Notify of
roshan

I created a frontend for my school project using jdbc drivers,i have a issue with the delete button.When i enter nothing in the text field and press the delete button Iam not getting a popup menu as an exception.
the code is pasted below,please suggest changes :
private void billdeleteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
Class.forName(“oracle.jdbc.driver.OracleDriver”);
int id=Integer.parseInt(billidtext.getText());
try (//step2 create the connection object
Connection con = DriverManager.getConnection(“jdbc:oracle:thin:localhost:xe”,”hr”,”****”)) {
Statement stmt=con.createStatement();
stmt = con.createStatement();
String sql = “DELETE FROM bill ” +
“WHERE bid = (‘”+id+”‘)”;
int w=stmt.executeUpdate(sql);
if(w!=0)
JOptionPane.showMessageDialog(null,”Deleted Successfully!”); //this is displayed successfully
else
JOptionPane.showMessageDialog(null,”value does not exists!”);// this is displayed successfully
supplieridtext.setText(“”);

//view trigger
String sql1=”SELECT * FROM bill”;

stmt = con.createStatement();

ResultSet rs = stmt.executeQuery(sql1);
//STEP 5: Extract data from result set
billtable.setModel(DbUtils.resultSetToTableModel(rs));
rs.close();

//step5 close the connection object
}

}catch( ClassNotFoundException | SQLException e){
JOptionPane.showMessageDialog(null,”no value entered!”);} //this line is not displayed when the text field is empty
}

Vote Up0Vote Down  Reply
2 years ago
Dhruv

package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import javax.swing.JOptionPane;

public class delete {
public static void main(String[] args) {
try {
Class.forName(“com.mysql.jdbc.Driver”);
Connection con=DriverManager.getConnection(“jdbc:mysql://localhost:3306/pacific”,”root”,”root”);
Statement st=con.createStatement();
int x=st.executeUpdate(“delete from login where username>=zz,password>=zz”);

if(x>0)
{
JOptionPane.showMessageDialog(null,”successfully deleted”);
}
} catch (Exception e) {
}
}

}

Vote Up0Vote Down  Reply
5 years ago
Siddu

How selected records stored in java?
Ex: select *from product. Say i have 10 records. How 10 records stored in java. Will it be array of 10 records or individual instance in java memory. Can We see internal details.

Vote Up0Vote Down  Reply
6 years ago
Siddu

How to return a resultset object from the stored procedure? Could you please explain.

Vote Up0Vote Down  Reply
6 years ago
Tony

Hi Siddu

String procName = “{call STORED_PRODURE_NAME(}”;
CallableStatement cs = conn.prepareCall(procName);
ResultSet rs = cs.executeQuery();

Then you can return ResultSet object.

Vote Up0Vote Down  Reply
6 years ago
Siddu

Hi Tony,
Thanks for reply.
How to take return values from stored procedure.. There is need to register out parameters.

Vote Up0Vote Down  Reply
6 years ago
Siddu

How to implement RowSet in JDBC?

Vote Up0Vote Down  Reply
6 years ago
Siddu

How to implement connection pooling in stand alone applications.

Vote Up0Vote Down  Reply
6 years ago
Tony

Yes Siddu this is a very good question.If any one knows kindly share with an example.

Vote Up0Vote Down  Reply
6 years ago
flex

Very simple, just create a Singleton class with HashMap where Object is an object that wraps a connection,and Integer – for example, its hashCode. In the wrapper – add a flag/counter is connection released. If in the Map there are released connetions – get one and re-use it; If not – create new, put in the Map and use it.

Vote Up0Vote Down  Reply
6 years ago

Search Tutorials

JDBC Tutorial

  • JDBC – Introduction
  • JDBC – MySQL Connection
  • JDBC – Types of Driver
  • JDBC – SQL SELECT Query
  • JDBC – SQL INSERT Query
  • JDBC – SQL DELETE Query
  • JDBC – PreparedStatement
  • JDBC – Optimization Tips

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Collections in Java
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Python Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap

wpDiscuz