表中的索引是指向数据的指针,这些指针加快了从表中检索数据的速度。如果使用索引,则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 { //注册驱动程序 Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); //获取连接对象 String URL = "jdbc:derby:MYDATABASE;create=true"; Connection conn = DriverManager.getConnection(URL); //创建Statement对象 Statement stmt = conn.createStatement(); //创建Emp表 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(" "); //列上创建索引 stmt.execute("CREATE INDEX example_index on Emp (Salary)"); System.out.println("Index example_index inserted"); System.out.println(" "); //列出所有索引 System.out.println("Listing all the columns with 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>