如何使用 JDBC API 删除数据库?
A. 你可以使用 DROP DATABASE 查询删除/删除数据库。
语法
DROP DATABASE DatabaseName;
要使用 JDBC API 删除数据库,您需要
注册驱动程序:使用 DriverManager 类的 registerDriver() 方法注册驱动程序类。将驱动程序类名作为参数传递给它。
建立连接:使用 DriverManager 类的 getConnection() 方法连接到数据库。将 URL(字符串)、用户名(字符串)、密码(字符串)作为参数传递给它。
创建语句:使用 Connection 接口的 createStatement() 方法创建一个 Statement 对象。
执行查询:使用 Statement 接口的 execute() 方法执行查询。
示例
show databases 命令会显示 MySQL 中的数据库列表。首先,使用此命令验证其中的数据库列表,如下所示:
mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | base | | details | | exampledatabase | | logging | | mydatabase | | mydb | | mysql | | performance_schema | | students | | sys | | world | +--------------------+ 12 rows in set (0.00 sec)
以下 JDBC 程序建立与 MySQL 的连接并删除名为 mydatabase 的数据库
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DropDatabaseExample {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql:///";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating the Statement
Statement stmt = con.createStatement();
//Query to drop a database
String query = "DROP database MyDatabase";
//Executing the query
stmt.execute(query);
System.out.println("Database dropped......");
}
}输出
Connection established...... Database Dropped......
如果您再次验证数据库列表,则在其中找不到 mydatabase 的名称,因为我们已将其删除。
mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | base | | details | | exampledatabase | | logging | | mydb | | mysql | | performance_schema | | students | | sys | | world | +--------------------+ 11 rows in set (0.00 sec)
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP