如何使用 JDBC 程序处理 JavaDB 中的索引?
jdbcobject oriented programmingprogramming
表中的索引是指向数据的指针,它们可以加快从表中检索数据的速度。如果我们使用索引,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"); //获取 Connection 对象 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 始终生成为 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(" "); //在 Salary 列上创建索引 stmt.execute(" CREATE INDEX example_index on Emp (Salary)"); System.out.println(" "); System.out.println(" "); //列出所有索引 System.out.println("列出所有带有索引的列"); //删除索引 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>