先把50000行数据写入数据库
package testJdbc;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class test {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String URL="jdbc:mysql://127.0.0.1:3306/homepage?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false";
//serverTimezone=GMT%2B8指调整时区,useSSL=false指ssl连接
String USER="root";
String PASSWORD="";
//1.加载驱动程序
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获得数据库链接
Connection conn=DriverManager.getConnection(URL, USER, PASSWORD);
if(conn!=null) {
System.out.println("连接成功");
insert(conn);
}else {
System.out.println("连接失败");
}
}
public static void insert(Connection conn) {
// 开始时间
// Date begin = new Date();
// sql前缀
try {
// 保存sql后缀
StringBuffer suffix = new StringBuffer();
// 设置事务为非自动提交
conn.setAutoCommit(false);
// 外层循环,总提交事务次数
for (int i = 1; i <= 5; i++) {
suffix = new StringBuffer();
// 第j次提交步长
for (int j = 1; j < 10000; j++) {
// 构建SQL后缀
suffix.append(" ( " + (int)(Math.random()*26) +'0' + ",'2019'," + j + ",'@qq.com','hunan') ,");
}
//不过java好像不能这样写?(int)(Math.random()*26) +'0'
String prefix = "insert into user (name,birth,phone,email,address) VALUES ";
// 构建完整SQL
String sql = prefix + suffix.substring(0, suffix.length() - 1);
// 添加执行SQL
// 比起st,pst会更好些
PreparedStatement pst = (PreparedStatement) conn.prepareStatement(sql);
// 准备执行语句
pst.addBatch(sql);
// 执行操作
pst.executeBatch();
// 提交事务
conn.commit();
// 清空上一次添加的数据
pst.close();
suffix = new StringBuffer();
}
// 头等连接
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
// 结束时间
// Long end = new Date(end).getTime();
// 耗时
// System.out.println("5万条数据插入花费时间 : " + (end - begin) / 1000 + " s");
System.out.println("插入完成");
}
}
插入结果
接下来是查找,可以看到,建立索引前是0.38s;建立索引之后是0.04s