一:使用map封装,这种方法使用于前端传值过来,然后封装批量插入
1:先创建对象
Map<String,Object> map = new HashMap<>();
Map<String, Object> params = new HashMap<>();
Test test = new Test();
test.setName("wawawa");
test.setAge("17");
2:将对象插入到map中,这里因为要在xml中取值,需要加一层封装
Long start = new Date().getTime();
for (int i=0;i<10000;i++){
map.put(""+i,test);
}
params.put("keys",map);
lmLoanService.save(params);
Long end = new Date().getTime();
System.out.println((end-start)/1000);
3:xml写法
<insert id="save" parameterType="hashmap">
INSERT INTO 表名 (name,age) VALUES
<foreach collection="keys" index="key" item="value" separator="," >
(#{value.name},#{value.age})
</foreach>
</insert>
4:测试数据为65秒一万条
二:第二种方法,用jdbc实现,如果只是生成测试数据,这种方法更优,一百万条数据,只需要几十秒即可,在字段不多的时候
public class Test {
private static Connection getConn() {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/etc";
String username = "etc";
String password = "123456";
Connection conn = null;
try {
Class.forName(driver); //classLoader,加载对应驱动
conn = (Connection) DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void insert() {
Connection conn = getConn();
// 开时时间
Long begin = new Date().getTime();
// sql前缀
String prefix = "INSERT INTO cms_test (name, age) VALUES ";
try {
// 保存sql后缀
StringBuffer suffix = new StringBuffer();
// 设置事务为非自动提交
conn.setAutoCommit(false);
// Statement st = conn.createStatement();
// 比起st,pst会更好些
PreparedStatement pst = conn.prepareStatement("");
// 外层循环,总提交事务次数
for (int i = 1; i <= 100; i++) {
// 第次提交步长
for (int j = 1; j <= 10000; j++) {
// 构建sql后缀
suffix.append('('+"\"帝云天\",\"33\""+"),");
}
// 构建完整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("cast : " + (end - begin) / 1000 + " s");
}
}
版权声明:本文为weixin_43703157原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。