如何使用 JDBC 程式處理 JavaDB 中的索引?


表中的索引指向資料,它們可以加快從表中檢索資料。如果我們使用索引,則 INSERT 和 UPDATE 語句將在速度較慢的階段執行。而 SELECT 和 WHERE 將在更短時間內執行。

建立索引

CTREATE INDEX index_name on table_name (column_name);

顯示索引

SHOW INDEXES FROM table_name;

刪除索引

DROP INDEX index_name;

以下 JDBC 程式在 JavaDB 中建立一個名為 Emp 的表。在其上建立一個索引,顯示索引列表,並刪除建立的索引。

示例

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class IndexesExample {
   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:MYDATABASE;create=true";
      Connection conn = DriverManager.getConnection(URL);
      //Creating the Statement object
      Statement stmt = conn.createStatement();
      //Creating the Emp table
      String createQuery = "CREATE TABLE Emp( "
         + "Id INT NOT NULL GENERATED ALWAYS AS IDENTITY, "
         + "Name VARCHAR(255), "
         + "Salary INT NOT NULL, "
         + "Location VARCHAR(255), "
         + "Phone_Number BIGINT )";
      stmt.execute(createQuery);
      System.out.println("Table created");
      System.out.println(" ");
      //Creating an Index on the column Salary
      stmt.execute("CREATE INDEX example_index on Emp (Salary)");
      System.out.println("Index example_index inserted");
      System.out.println(" ");
      //listing all the indexes
      System.out.println("Listing all the columns with indexes");
      //Dropping indexes
      stmt.execute("Drop INDEX example_index ");
   }
}

輸出

On executing, this generates the following result
Table created
Index example_index inserted
Listing all the columns with indexes>

更新於:30-Jul-2019

912 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告