如何使用 Java 刪除 MySQL 表?


首先讓我們建立一個數據庫中的表。建立表的查詢如下

mysql> create table customerDetails
   -> (
   -> CustomerId int,
   -> CustomerName varchar(30)
   -> );
Query OK, 0 rows affected (0.56 sec)

現在從資料庫中顯示所有表,以便檢查是否存在 customerDetails 表。

查詢如下

mysql> show tables;

以下是輸出

+------------------------------+
| Tables_in_test3              |
+------------------------------+
| bestdateformatdemo           |
| customerdetails              |
| deletedemo                   |
| differentdatetime            |
| expandedoutputdemo           |
| fieldlessthan5chars          |
| lastrecordbeforelastone      |
| mostrecentdatedemo           |
| nullcasedemo                 |
| order                        |
| orderbydatethentimedemo      |
| posts                        |
| productdemo                  |
| radiansdemo                  |
| selecttextafterlastslashdemo |
| siglequotesdemo              |
| studentinformation           |
| updatestringdemo             |
+------------------------------+
18 rows in set (0.00 sec)

檢視示例輸出,我們有“customerdetails”表。

以下是刪除表的 Java 程式碼。我們的資料庫是 test3

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class DropTableDemo {
   public static void main(String[] args) {
      Connection con = null;
      PreparedStatement ps = null;
      try {
         con = DriverManager.getConnection("jdbc:mysql://:3306/test3?useSSL=false", "root", "123456");
         ps = con.prepareStatement(
         String.format("DROP TABLE IF EXISTS %s", "customerdetails"));
         boolean result = ps.execute();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

現在檢視資料庫 test3,檢查是否存在表“customerDetails”,因為我們已在上面將其刪除。

查詢如下

mysql> show tables;

以下是輸出

+------------------------------+
| Tables_in_test3              |
+------------------------------+
| bestdateformatdemo           |
| deletedemo                   |
| differentdatetime            |
| expandedoutputdemo           |
| fieldlessthan5chars          |
| lastrecordbeforelastone      |
| mostrecentdatedemo           |
| nullcasedemo                 |
| order                        |
| orderbydatethentimedemo      |
| posts                        |
| productdemo                  |
| radiansdemo                  |
| selecttextafterlastslashdemo |
| siglequotesdemo              |
| studentinformation           |
| updatestringdemo             |
+------------------------------+
17 rows in set (0.00 sec)

是的,我們已成功從資料庫 test3 中刪除“customerDetails”表。

更新日期:30-7-2019

232 次瀏覽

開啟您的 職業生涯

完成課程,獲得認證

立即開始
廣告
© . All rights reserved.