数据库查询速度的比较

       向数据库中插入n条记录,比较有索引和没有索引的查询时间

      向数据库中插入n条记录,肯定不是自己手动一条一条的加,当然是使用java编程

       首先创建一个表:

       

        把id设置成主键,主键自带索引,或者添加索引

      插入n条记录的代码如下:

import static org.junit.Assert.*;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.mysql.jdbc.Connection;


public class TestJDBC {
    private Connection con;
    @Before
    public void setUp() throws Exception {
        con=DriverManager.getConnection("jdbc:mysql://localhost:3306/one","root","root");
    }

    @After
    public void tearDown() throws Exception {
    con.close();
    }

    @Test
    public void test() throws SQLException {
        Statement stat=con.createStatement();
        StringBuilder sb=new StringBuilder();
        for(int i=10001;i<=20000;i++)
        {
            sb.append("('hahaha"+i+"')");
            if(i!=20000)
            {
                sb.append(",");
            }
        }
        
        stat.executeUpdate("insert into tb_jdbc1(name) values"+sb.toString());
    }

通过索引查询:

没有索引查询:

 由此看出有索引查询和没有索引查询时间之差是0.01s

 当我们把索引的方式设置成betree时:

 通过主键查询:

 不用主键查询:

时间之差为0.021s

由以上证明有索引的查询速度更快

原文地址:https://www.cnblogs.com/xiaojuzibuxiao/p/7792193.html