如何使用 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://127.0.0.1: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”表。
广告