Apache Derby - 刪除表



DROP TABLE 語句用於刪除現有表,包括其所有觸發器、約束和許可權。

語法

以下是 DROP TABLE 語句的語法。

ij> DROP TABLE table_name;

示例

假設資料庫中有一個名為 Student 的表。以下 SQL 語句將刪除名為 Student 的表。

ij> DROP TABLE Student;
0 rows inserted/updated/deleted

由於我們已刪除該表,如果嘗試描述它,將會收到如下錯誤。

ij> DESCRIBE Student;
IJ ERROR: No table exists with the name STUDENT

使用 JDBC 程式刪除表

本節將教您如何使用 JDBC 應用程式刪除 Apache Derby 資料庫中的表。

如果要使用網路客戶端請求 Derby 網路伺服器,請確保伺服器正在執行。網路客戶端驅動程式的類名為 org.apache.derby.jdbc.ClientDriver,URL 為 jdbc:derby://:1527/DATABASE_NAME;create=true;user=USER_NAME;password=PASSWORD"

請按照以下步驟在 Apache Derby 中刪除表:

步驟 1:註冊驅動程式

要與資料庫通訊,首先需要註冊驅動程式。Class 類的 forName() 方法接受表示類名的字串值,將其載入到記憶體中,這會自動註冊它。使用此方法註冊驅動程式。

步驟 2:獲取連線

通常,與資料庫通訊的第一步是連線到它。Connection 類表示與資料庫伺服器的物理連線。您可以透過呼叫 DriverManager 類的 getConnection() 方法來建立連線物件。使用此方法建立連線。

步驟 3:建立語句物件

您需要建立 Statement、PreparedStatement 或 CallableStatement 物件才能將 SQL 語句傳送到資料庫。您可以分別使用 createStatement()、prepareStatement() 和 prepareCall() 方法建立這些物件。使用適當的方法建立這些物件中的任何一個。

步驟 4:執行查詢

建立語句後,需要執行它。Statement 類提供各種方法來執行查詢,例如 execute() 方法來執行返回多個結果集的語句。executeUpdate() 方法執行 INSERT、UPDATE、DELETE 等查詢。executeQuery() 方法返回資料的查詢結果等。使用這些方法中的任何一個並執行先前建立的語句。

示例

以下 JDBC 示例演示瞭如何使用 JDBC 程式在 Apache Derby 中刪除表。在這裡,我們使用嵌入式驅動程式連線到名為 sampleDB 的資料庫(如果不存在則會建立)。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class DropTable {
   public static void main(String args[]) throws Exception {
      //Registering the driver
      Class.forName("org.apache.derby.jdbc.EmbeddedDriver");

      //Getting the Connection object
      String URL = "jdbc:derby:sampleDB;create=true";
      Connection conn = DriverManager.getConnection(URL);

      //Creating the Statement object
      Statement stmt = conn.createStatement();

      //Executing the query
      String query = "DROP TABLE Employees";
      stmt.execute(query);
      System.out.println("Table dropped");
   }
}

輸出

執行上述程式後,您將獲得以下輸出:

Table dropped
廣告
© . All rights reserved.