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