Delete records from database using JDBC

Introduction 

 
In this blog we will know how to delete records from database using JDBC (Java Database Connectivity) in the console window.
 
Here we use Type-1 driver (JDBC-ODBC bridge)
 

Creation of dsn(database source name) for Oracle

 
Start-Control panel- Administrative Tools- Data Sources (ODBC)-go to system DSN tab-click add button-select a driver for which you want to set up a data source (for Oracle- Oracle in XE)-select it and click finish-give any name in the data source name textbox-then click ok button.
 
Note: - Here Username=system, Password=pintu and DSN name=dsn1
 

Table Creation

 
Create table employee (empno int,empname varchar(50),sal int)
 
Example:- To delete record from a table
  1. /*To delete record from a table by using Statement*/  
  2. import java.sql.*;  
  3. import java.util.*;  
  4. public class delete {  
  5.  public static void main(String args[]) throws Exception {  
  6.   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  
  7.   Scanner sc = new Scanner(System.in);  
  8.   Connection con = DriverManager.getConnection("jdbc:odbc:dsn1""system""pintu");  
  9.   Statement stmt = con.createStatement();  
  10.   System.out.print("Enter lower limit salary: ");  
  11.   int lb = sc.nextInt();  
  12.   System.out.print("Enter upper limit salary: ");  
  13.   int ub = sc.nextInt();  
  14.   String sql = "delete from employee where sal between " + lb + " and " + ub;  
  15.   int no = stmt.executeUpdate(sql);  
  16.   System.out.println(no + " Records Successfully Deleted...");  
  17.   con.close();  
  18.  }  
  19. }   
Compile
 
Javac delete.java
Java delete