如何使用 Java 删除 MySQL 表?
mysqlmysqli database
首先让我们在数据库中创建一个表。创建表的查询如下
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://localhost: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’表。