1.将数据库连接驱动、druid的jar包、dbutils包添加到项目库中。
2.创建druid.properties
#key=value
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/student?rewriteBatchedStatements=true
username=root
password=root
initialSize=10
minIdle=5
maxActive=20
maxWait=5000
3.创建druid的utils类。
package com.aura.druid.utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* @author panghu
* @description druid连接池的工具类
* @create 2021-01-30-12:12
*/
public class DruidUtils {
public static Connection getConnection() throws Exception {
Properties prop = new Properties();
prop.load(DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
DataSource ds = DruidDataSourceFactory.createDataSource(prop);
Connection conn = ds.getConnection();
return conn;
}
public static void closeAll(Connection conn, Statement st, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
4.批处理
package com.aura.druid.demo;
import com.aura.druid.utils.DruidUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
/**
* @author panghu
* @description druid批处理数据
* @create 2021-01-30-12:19
*/
public class DruidTest3 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = DruidUtils.getConnection();
String sql = "INSERT INTO grade VALUES(?,?)";
ps = conn.prepareStatement(sql);
for (int i=1;i<=502;i++){
ps.setInt(1,i);
ps.setString(2,i+"年级");
ps.addBatch();//开启批处理
if(i % 100 == 0){ //最后的两条数据没有插入
ps.executeBatch();//处理一批数据
ps.clearBatch();//清空处理完数据的缓存
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DruidUtils.closeAll(conn,ps,null);
}
}
}