如何在 MySQL 資料庫中使用 Java 刪除資料?


在 DELETE 命令的幫助下從 MySQL 資料庫中刪除資料。語法如下。

delete from yourTableName where condition;

我將透過 Java 程式語言在 MySQL 資料庫中刪除資料。首先,建立一個表並插入一些記錄。以下是要建立表的查詢。

mysql> create table DeleteTableDemo
   -> (
   -> id int,
   -> Name varchar(200)
   -> );
Query OK, 0 rows affected (0.94 sec)

在上述表中插入記錄。插入記錄的查詢如下。

mysql> insert into DeleteTableDemo values(101,'Smith');
Query OK, 1 row affected (0.21 sec)

mysql> insert into DeleteTableDemo values(102,'Johnson');
Query OK, 1 row affected (0.27 sec)

現在,我們可以檢查我的表中有多少條記錄。查詢如下。

mysql> select *from DeleteTableDemo;

以下是輸出。

+------+---------+
| id   | Name    |
+------+---------+
|  101 | Smith   |
|  102 | Johnson |
+------+---------+
2 rows in set (0.00 sec)

表中有兩條記錄。現在,讓我們在 delete 命令的幫助下從 MySQL 資料庫表中刪除資料。以下是使用 id=101 刪除資料的 JAVA 程式碼。在執行該操作之前,我們將建立一個 Java 連線到我們的 MySQL 資料庫。

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
public class JavaDeleteDemo {
   public static void main(String[] args) {
       Connection conn = null;
      Statement stmt = null;
       try {
          try {
             Class.forName("com.mysql.jdbc.Driver");
          } catch (Exception e) {
             System.out.println(e);
          }
          conn = (Connection) DriverManager.getConnection("jdbc:mysql:///business", "Manish", "123456");
          System.out.println("Connection is created successfully:");
          stmt = (Statement) conn.createStatement();
          String query1 = "delete from  DeleteTableDemo " +
          "where id=101";
          stmt.executeUpdate(query1);
          System.out.println("Record is deleted from the table successfully..................");
       } catch (SQLException excep) {
          excep.printStackTrace();
       } catch (Exception excep) {
          excep.printStackTrace();
       } finally {
          try {
             if (stmt != null)
             conn.close();
          } catch (SQLException se) {}
          try {
             if (conn != null)
             conn.close();
          } catch (SQLException se) {
             se.printStackTrace();
          }
       }
       System.out.println("Please check it in the MySQL Table. Record is now deleted.......");
    }
}

以下是輸出。

mysql> select *from DeleteTableDemo;

以下是輸出。

+------+---------+
| id   | Name |
+------+---------+
| 102  |Johnson |
+------+---------+
1 row in set (0.00 sec) We have deleted the data with id 101.

更新日期: 2020 年 6 月 26 日

5000+ 次瀏覽

開始您的 職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.