HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / JDBC / JDBC SQL DELETE Query Example

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

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

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

Feedback, Discussion and Comments

  1. roshan

    November 25, 2017

    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
    }

  2. Dhruv

    October 25, 2014

    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) {
    }
    }

    }

  3. Siddu

    November 24, 2013

    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.

  4. Siddu

    November 24, 2013

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

    • Tony

      November 24, 2013

      Hi Siddu

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

      Then you can return ResultSet object.

      • Siddu

        November 24, 2013

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

  5. Siddu

    November 24, 2013

    How to implement RowSet in JDBC?

  6. Siddu

    November 24, 2013

    How to implement connection pooling in stand alone applications.

    • Tony

      November 24, 2013

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

    • flex

      December 1, 2013

      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.

Comments are closed on this article!

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

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

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 © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces