如何使用 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)

更新於: 2019-07-30

264 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.