B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP JDBC Delete Record with Before & After Display | Login Technologies

JDBC Delete Record with Display Before and After in Java

This example shows how to display all records from the students table before and after deleting a record using JDBC in Java.

यह उदाहरण JDBC का उपयोग करके रिकॉर्ड डिलीट करने से पहले और बाद में students टेबल के सभी रिकॉर्ड दिखाता है।

Java Code to Display Records, Delete One, and Display Again

import java.sql.*;

public class JdbcDeleteWithDisplay {
  public static void main(String[] args) {
    String url = "jdbc:mysql://localhost:3306/studentdb";
    String user = "root";
    String password = "your_mysql_password";

    try {
      Class.forName("com.mysql.cj.jdbc.Driver");
      Connection con = DriverManager.getConnection(url, user, password);

      // Display records before deletion
      System.out.println("Before Deletion:");
      displayRecords(con);

      // Delete record with id=3
      String sqlDelete = "DELETE FROM students WHERE id = ?";
      PreparedStatement pstmt = con.prepareStatement(sqlDelete);
      pstmt.setInt(1, 3);
      int rowsDeleted = pstmt.executeUpdate();
      System.out.println("\n" + rowsDeleted + " record(s) deleted.\n");

      // Display records after deletion
      System.out.println("After Deletion:");
      displayRecords(con);

      con.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void displayRecords(Connection con) throws SQLException {
    String sqlSelect = "SELECT * FROM students ORDER BY id";
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery(sqlSelect);

    System.out.println("+----+--------+");
    System.out.println("| id | name   |");
    System.out.println("+----+--------+");
    while (rs.next()) {
      System.out.printf("| %-2d | %-6s |\n", rs.getInt("id"), rs.getString("name"));
    }
    System.out.println("+----+--------+");
  }
}

In this program, the displayRecords() method is used to print the current records from the students table. The program deletes the record with id = 3, then shows the updated table.

इस प्रोग्राम में displayRecords() मेथड का उपयोग वर्तमान रिकॉर्ड्स दिखाने के लिए किया गया है। यह id = 3 वाला रिकॉर्ड डिलीट करता है और फिर अपडेटेड टेबल दिखाता है।

✅ Expected Console Output
Before Deletion:
+----+--------+
| id | name   |
+----+--------+
| 1  | Aryan  |
| 2  | Riya   |
| 3  | Amit   |
+----+--------+

1 record(s) deleted.

After Deletion:
+----+--------+
| id | name   |
+----+--------+
| 1  | Aryan  |
| 2  | Riya   |
+----+--------+