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.
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 !!
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
}
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) {
}
}
}
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.
Siddu
How to return a resultset object from the stored procedure? Could you please explain.
Tony
Hi Siddu
String procName = “{call STORED_PRODURE_NAME(}”;
CallableStatement cs = conn.prepareCall(procName);
ResultSet rs = cs.executeQuery();
Then you can return ResultSet object.
Siddu
Hi Tony,
Thanks for reply.
How to take return values from stored procedure.. There is need to register out parameters.
Siddu
How to implement RowSet in JDBC?
Siddu
How to implement connection pooling in stand alone applications.
Tony
Yes Siddu this is a very good question.If any one knows kindly share with an example.
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.