MyBatis--批量新增数据
程序员文章站
2022-03-10 18:38:20
...
主要内容:
JDBC插入数据方法:
传统JDBC进行批量数据插入:
1、使用For循环
package jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
/**
* Created by imooc
*/
public class BatchTestOne {
public static void main(String[] args) throws Exception {
Connection conn=null;
PreparedStatement preparedStatement=null;
conn=JdbcUtil.getConnection();
JdbcUtil.begin(conn);
String sql="insert into t_user(username,password) values(?,?)";
preparedStatement=conn.prepareStatement(sql);
long beginTime=System.currentTimeMillis();
for (int i = 0; i <10000 ; i++)
{
preparedStatement.setString(1,"hello"+(i+1));
preparedStatement.setString(2,"world"+(i+1));
preparedStatement.executeUpdate();
}
JdbcUtil.commit(conn);
long endTime=System.currentTimeMillis();
System.out.println("total time:"+(endTime-beginTime));
}
}
2、使用批处理方法addBatch:
package jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
/**
* 使用addBatch方法进行操作
*/
public class BatchTestTwo {
public static void main(String[] args) throws Exception {
Connection conn=null;
PreparedStatement preparedStatement=null;
conn=JdbcUtil.getConnection();
JdbcUtil.begin(conn);//autocommit false
String sql="insert into t_user(username,password) values(?,?)";
preparedStatement=conn.prepareStatement(sql);
long beginTime=System.currentTimeMillis();
for (int i = 0; i <10000 ; i++)
{
preparedStatement.setString(1,"hello"+(i+1));
preparedStatement.setString(2,"world"+(i+1));
preparedStatement.addBatch();
if((i+1)%500==0)
{
preparedStatement.executeBatch();
preparedStatement.clearBatch();
}
}
//如果数据是10001条,不能刚好被500整除,还会剩一些数据没有在循环中被执行
//所以此处需要再执行下面的语句
preparedStatement.executeBatch();
preparedStatement.clearBatch();
long endTime=System.currentTimeMillis();
System.out.println(endTime-beginTime);
JdbcUtil.commit(conn);
}
}
总结:
使用MyBatis进行批量插入:
1、
2、
使用ExecutorType进行批量添加: