一、传统JDBC进行批处理操作
package jdbc;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class jdbcUtil {
private static class JdbcUtil {
}
//处理数据库事务,提交事务
public static void commit(Connection conn) {
if (null != conn) {
try {
conn.commit();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
//事务的回滚
public static void rollback(Connection conn) {
if (null != conn) {
try {
conn.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
//事务的开始
public static void begin(Connection conn) {
if (null != conn) {
try {
conn.setAutoCommit(false);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
/**
* 获取数据库的连接
*/
public static Connection getConnection() throws Exception {
Properties properties = new Properties();
//速度快的方式
//new fileinputStream()
InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
//jdbc文件 内容 以流的方式加载到properties文件中
properties.load(is);
String driver = properties.getProperty("driver");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
public static void closeResources(Connection conn, Statement statement, ResultSet resultSet){
if (null!=resultSet){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (null!=statement){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(null!=conn){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
for循环插入1万条数据
方法二:addBatch()
package jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
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();
//当每达到1000条就提交
for(int i=0;i<10000;i++){
preparedStatement.setString(1,"hello"+i);
preparedStatement.setString(2,"world"+i);
preparedStatement.executeUpdate();
}
jdbcUtil.commit(conn);
long endTime = System.currentTimeMillis();
System.out.println(endTime-beginTime);//1537
}
}
传统利用for循环进行插入,存在严重效率问题,需要频繁获取Session,获取连接
使用批处理,代码和SQL的耦合,代码量较大
Mybatis批量插入
-
借助foreach标签使用 insert into table values()
借助mysql这样的方式插入数据。
方法二 借助MySQL数据库连接属性allowMultiQueries=true
借助mysql这样的方式插入数据
直接把insert into移到里边
基于SqlSession的ExecutorType进行批量添加