索引是数据库的一个对象,索引在数据库中起到向导作用。其主要目的是为了提高对数据库中数据的查询速度,例如:我们在咋点钟查询一个汉字时,通常会先利用文字的偏方部首,汉语拼音来查询,在数据库中,索引就起到了偏旁部首和拼音的作用。但也会降低数据的插入速度。
索引一般会应用在有主键和唯一约束的情况中,在频繁使用对数据库进行查询时索引的应用至关重要。mysql中一般有两种索引方式,一种是hash索引,另一种是btree索引,其中hash索引较适合等值查询,btree适合范围查询。
如下是利用java通过jdbc的链接对数据库进行的有索引和无索引查询,并查看其速度:
1、数据库的连接
package forjdbc;
import static org.junit.Assert.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class Testsuoyin {
private static Connection conn;
@Before
public void setUp() throws Exception {
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/for1031","root","root");
}
@After
public void tearDown() throws Exception {
conn.close();
}
2、向数据库中的表格中插入1万条数据
@Test
public void test() throws SQLException {
Statement st=conn.createStatement();
for(int i=0;i<100000;i++){
st.execute("insert into stu (id,name) values ("+i+",'haha"+i+"')");//向表stu中插入数据
}
}
3、有索引查询
@Test
public void test1() throws SQLException {
Statement st=conn.createStatement();
long l1=System.currentTimeMillis();//查询千的时间
st.executeQuery("select * from stu where id=50012");//id是索引,此处为有索引查询
long l2=System.currentTimeMillis();//查询后的时间
System.out.println(l2-l1);
}
4、无索引查询
@Test
public void test2() throws SQLException {
Statement st=conn.createStatement();
long l1=System.currentTimeMillis();//查询千的时间
st.executeQuery("select * from stu where name='haha50012'");//name不是索引,此处为无索引查询
long l2=System.currentTimeMillis();//查询后的时间
System.out.println(l2-l1);
}
}
查询结果:
通过结果不难看出有索引的查询速度比不用索引的查询速度快。