Delete Record JDBC Example

Delete Record JDBC Example. The Employee ID is taken from keyboard input.
Example on Delete Record JDBC Example
import java.sql.*;
import java.io.*;

public class DeleteRecord
{
  public static void main(String args[]) throws Exception
  {                                               // to take input from the user
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    System.out.println("Please Enter the ID no:");
    String str=br.readLine();
    int num = Integer.parseInt(str);
		                                  // 3 standard JDBC statements
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con=DriverManager.getConnection("jdbc:odbc:snrao","scott","tiger");
    Statement stmt=con.createStatement();
                                                 // send SQL command
    int affectedRecords = stmt.executeUpdate("delete from Employee where empid=" + num);
						// printing message for the user
    System.out.println("Number " + num + " record deleted");
    System.out.println("Number of records deleted: " + affectedRecords);
    br.close();
    stmt.close();
    con.close();
  }
} 


Delete Record JDBC Example
Output screen of Delete Record JDBC Example

int affectedRecords = stmt.executeUpdate(“delete from Employee where empid=” + num);

Write the variable num outside the string. At runtime, the num is exchanged with the actual value and concatenated to the string and forms an SQL query. This is seen in Java Inserting Records with Keyboard Input while writing insert command. The above statement can be modified like this also to delete a range.

int affectedRecords = stmt.executeUpdate(“delete from Employee where empid>”+num);

executeUpdate(String) returns an integer value equivalent to the number of records affected in the database table with the update command.

Note 1: Before going into the program, it is advised to go through JDBC Programming Basic Steps where the meaning of Connection, Statement etc. are discussed.

Note 2: To know how to use try-catch-finally with the above code, example program is available at JDBC Example – Create Table.

Leave a Comment

Your email address will not be published.