JDBC批处理
概述
JDBC操作数据库的时候,需要一次性插入大量的数据的时候,如果
每次只执行一条sql语句,效率就会很低。使用batch操作,每次批
量执行SQL语句,调高效率
Statement和PrepareStatement都可以使用批处理
PrepareStatement常用方法:
addBatch(); //积攒sql语句
executeBatch(); // 执行批处理
clearBatch(); // 清空批处理
- 首先在连接数据库的配置文件中加入如下代码
rewriteBatchedStatements=true
Durid连接池工具类
public class JDBCUtils_Durid {
static DataSource dataSource =null;
static ThreadLocal<Connection> tl = new ThreadLocal<>();
static {
Properties pro = new Properties();
InputStream in = JDBCUtils_Durid.class.getClassLoader().getResourceAsStream("durid.properties");
try {
pro.load(in);
dataSource = DruidDataSourceFactory.createDataSource(pro);
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取连接
public static Connection getConnection() throws SQLException, IOException {
Connection con = tl.get();
if (con == null) {
con = dataSource.getConnection();
tl.set(con);
}
return con;
}
// 释放连接
public static void closeResource(ResultSet rs, Statement st, Connection con) throws SQLException {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
tl.remove();
con.close();
}
}
}
使用Durid连接池和batch批处理插入数据
public class Durid_batch {
@Test
public void test0() throws SQLException, IOException {
// 获取连接
Connection con = JDBCUtils_Durid.getConnection();
PreparedStatement ps = con.prepareStatement("insert into account values(?,null,?)");
long startTime = System.currentTimeMillis();
for (int i = 1; i < 10000; i++) {
ps.setInt(1,i);
ps.setDouble(2,i);
// 积攒 sql语句
ps.addBatch();
// 如果除不尽的话,最后一部分不足3000的数据是不会被写入的
if(i % 3000 == 0){
System.out.println(i);
// 执行批处理
ps.executeBatch();
// 清空批处理
// ps.clearBatch();
}
}
// 处理最后一部分小于除数的数据
ps.executeBatch();
ps.clearBatch();
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
// 关闭连接
JDBCUtils_Durid.closeResource(null,ps,con);
// truncate table account 清空数据表
}
}
引用:https://blog.csdn.net/lizhiqiang1217/article/details/90550465