如何使用 JDBC API 從資料庫中現有表中刪除記錄?


您可以使用 DELETE 查詢從資料庫中的表中刪除特定記錄。

語法

DELETE FROM table_name
WHERE [condition];

要使用 JDBC API 從表中刪除記錄,您需要

  • 註冊驅動程式:使用 DriverManager 類的 registerDriver() 方法註冊驅動程式類。將驅動程式類名作為引數傳遞給它。

  • 建立連線:使用 DriverManager 類的 getConnection() 方法連線到資料庫。將 URL(字串)、使用者名稱(字串)、密碼(字串)作為引數傳遞給它。

  • 建立語句:使用 Connection 介面的 createStatement() 方法建立一個 Statement 物件。

  • 執行查詢:使用 Statement 介面的 executeUpdate() 方法執行查詢。

示例

假設我們在名為 mydatabase 的 MySQL 資料庫中有一個名為 customers 的表,其中包含 12 條記錄,如下所示

+----+-----------+------+---------+----------------+
| ID | NAME      | AGE  | SALARY  | ADDRESS        |
+----+-----------+------+---------+----------------+
| 1  | Amit      | 25   | 3000.00 | Hyderabad      |
| 2  | Kalyan    | 27   | 4000.00 | Vishakhapatnam |
| 3  | Renuka    | 30   | 5000.00 | Delhi          |
| 4  | Archana   | 24   | 1500.00 | Mumbai         |
| 5  | Koushik   | 30   | 9000.00 | Kota           |
| 6  | Hardik    | 45   | 6400.00 | Bhopal         |
| 7  | Trupthi   | 33   | 4360.00 | Ahmedabad      |
| 8  | Mithili   | 26   | 4100.00 | Vijayawada     |
| 9  | Maneesh   | 39   | 4000.00 | Hyderabad      |
| 10 | Rajaneesh | 30   | 6400.00 | Delhi          |
| 11 | Komal     | 29   | 8000.00 | Ahmedabad      |
| 12 | Manyata   | 25   | 5000.00 | Vijayawada     |
+----+-----------+------+---------+----------------+

以下 JDBC 程式建立與 MySQL 資料庫的連線,並刪除工資值小於 5000 的客戶的記錄,在刪除操作後檢索並顯示錶的內容。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DeleteRecordsExample {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql:///MyDatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating the Statement
      Statement stmt = con.createStatement();
      //Query to delete records
      String query = "Delete from customers where salary < 5000";
      int i = stmt.executeUpdate(query);
      System.out.println("Rows deleted: "+i);
      //Retrieving data
      ResultSet rs = stmt.executeQuery("Select * from customers");
      System.out.println("Contents of the table after deleting the records: ");
   }
}

輸出

Connection established......
Rows deleted: 6
Contents of the table after deleting the records:
ID: 3, Name: Renuka, Age: 30, Salary: 5000, Address: Delhi
ID: 5, Name: Koushik, Age: 30, Salary: 9000, Address: Kota
ID: 6, Name: Hardik, Age: 45, Salary: 6400, Address: Bhopal
ID: 10, Name: Rajaneesh, Age: 30, Salary: 6400, Address: Delhi
ID: 11, Name: Komal, Age: 29, Salary: 8000, Address: Ahmedabad
ID: 12, Name: Manyata, Age: 25, Salary: 5000, Address: Vijayawada

更新於: 2019-07-30

313 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.