如何使用 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.