好记性不如乱笔头
当一张表中包含了千万级别的数据时,查询的速度比乌龟爬快不了多少。这个时候就需要索引了。
直接开干
1. 表结构入下,password写成了passwrd,懒得改了,勿喷。
- 咱们就插入1000万条数据吧,怎么插入呢?可别想着一条一条的插入啊,保证你不会砸电脑,哈哈。
a. 存储过程,这个知识吗,还给大学老师了。
b. java代码直接插入(提交事务的方式,速度还挺快的)。
直接上代码,亲测插入1000条万数据100秒。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyTest {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
final String url = "jdbc:mysql://localhost:3306/school?characterEncoding=UTF-8";
final String name = "com.mysql.jdbc.Driver";
final String user = "root";
final String password = "fx19950103";
Connection conn = null;
Class.forName(name);//指定连接类型
conn = DriverManager.getConnection(url, user, password);//获取连接
if (conn!=null) {
System.out.println("获取连接成功");
insert(conn);
}else {
System.out.println("获取连接失败");
}
}
public static void insert(Connection conn) {
// 开始时间
Long begin = new Date().getTime();
// sql前缀
String prefix = "INSERT INTO user (name,passwrd) VALUES ";
try {
// 保存sql后缀
StringBuffer suffix = new StringBuffer();
// 设置事务为非自动提交
conn.setAutoCommit(false);
// 比起st,pst会更好些
PreparedStatement pst = (PreparedStatement) conn.prepareStatement("");//准备执行语句
// 外层循环,总提交事务次数
for (int i = 1; i <= 1000; i++) {
suffix = new StringBuffer();
// 第j次提交步长
for (int j = 1; j <= 10000; j++) {
// 构建SQL后缀
suffix.append("('" +"fx"+(i*j)+"','p" +(i+j)+"'"+"),");
}
// 构建完整SQL
String sql = prefix + suffix.substring(0, suffix.length() - 1);
// System.out.println(sql);
// 添加执行SQL
pst.addBatch(sql);
// 执行操作
pst.executeBatch();
// 提交事务
conn.commit();
// 清空上一次添加的数据
suffix = new StringBuffer();
}
// 头等连接
pst.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
// 结束时间
Long end = new Date().getTime();
// 耗时
System.out.println("1000万条数据插入花费时间 : " + (end - begin) / 1000 + " s");
System.out.println("插入完成");
}
}
- 现在我们查询name = ‘fx77777777777’【这个数据是我随便在里面改的一条】
select * from `user` where name = 'fx77777777777'
亲测,花了6.03秒。我的天,这么久,不能忍啊。
- 大招,建立索引。
ALTER TABLE
userADD INDEX index_name (
name)
index_name是索引的名字,’name‘是字列名。
亲测,建立索引很耗费时间,花了46秒。
然后再查询一次,很神奇的发现仅仅只花了0.003秒,真牛叉。
小提示:就只是很简单的使用了一般索引,还有别的索引类型哦,索引还有挺多要注意的地方,自己查资料吧。