背景
产品需求:生成一串不重复的号码0-19999999且不能有超过3位以上的豹子号连号。当消耗一半后需要多少秒才能插入一条数据;
首先的问题就是,先要插入1000万条数据。
我首先生成1000万条数据然后在入库,花费时间8分钟。
步骤1:数据库连接
//调用该方法生成1000万条数据
public void inset1000WUser() {
//Set<String> gettestzx = gettestzx();//这是我自己生成1000万个不重复数字的方法
//List<String> list = new ArrayList<>(gettestzx);
final String url = "你自己的数据库连接地址";
//jdbc:mysql://00.0.00.00:3306/****?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull
final String name = "com.mysql.jdbc.Driver";
final String user = "你自己的用户名";
final String password = "你自己的密码";
Connection conn = null;
try {
Class.forName(name);//指定连接类型
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
try {
conn = DriverManager.getConnection(url, user, password);//获取连接
} catch (SQLException e) {
throw new RuntimeException(e);
}
if (conn != null) {
System.out.println("获取连接成功");
//insert(conn,list);
insert(conn);
} else {
System.out.println("获取连接失败");
}
}
步骤2:插入数据方法
//private void insert(Connection conn,List<String> list ) {
private void insert(Connection conn) {
// 开始时间
Long begin = System.currentTimeMillis();
// sql前缀
//String prefix = "INSERT INTO user_role (id, num) VALUES ";
String prefix = "INSERT INTO 你的表名 (你的字段名1, 你的字段名2) VALUES ";
try {
// 保存sql后缀
StringBuffer suffix = new StringBuffer();
// 设置事务为非自动提交
conn.setAutoCommit(false);
// 比起st,pst会更好些
PreparedStatement pst = (PreparedStatement) conn.prepareStatement(" ");//准备执行语句
// 外层循环,总提交事务次数,可以修改
for (int i = 1; i <= 10; i++) {
suffix = new StringBuffer();
// 第j次提交步长
for (int j = 1; j <= 1000000; j++) {
// 构建SQL后缀
//suffix.append("('" + snowflake.nextId() + "'," + list.get(j-1) + "),");
suffix.append("('" + 你的字段值1 + "'," + 你的字段值2 + "),");
}
// 构建完整SQL
String sql = prefix + suffix.substring(0, suffix.length() - 1);
// 添加执行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("插入完成");
}
步骤3:调用他就完事了