Java如何从数据库中删除表?
本示例向您展示如何从数据库中删除或删除表。基本上,我们只是发送DROPTABLE命令并指定要删除到数据库的表名。下面的示例向您展示如何在MySQL数据库中进行操作。
package org.nhooo.example.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class DropTableExample { private static final String URL = "jdbc:mysql://localhost/nhooo"; private static final String USERNAME = "root"; private static final String PASSWORD = ""; public static void main(String[] args) { try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD)) { //要从数据库中删除表,我们使用DROPTABLE //命令并指定要删除的表名 String sql = "DROP TABLE books"; //建立陈述 Statement statement = connection.createStatement(); //执行该语句删除表 statement.execute(sql); } catch (SQLException e) { e.printStackTrace(); } } }
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency>