如何使用 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”表。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP