如何使用Java删除MySQL表?
让我们首先在数据库中创建一个表。创建表的查询如下
create table customerDetails -> ( -> CustomerId int, -> CustomerName varchar(30) -> );
现在显示数据库中的所有表,以检查customerDetails表是否存在。
查询如下
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'是否存在,因为我们已经在上面删除了它。
查询如下
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'表。