jdbc批量作数据库
1.jdbc连接
package com.test.utils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
@Component
public class ConnectionUtils {
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driver-class-name}")
private String driver ;
public Connection connect(){
try {
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
if(conn!=null){
return conn;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
}
2.操作数据库
@Autowired
private ConnectionUtils jdbcUtils;
@Test
public void batch() {
List list = new ArrayList<>();
for (int i = 0; i < 1000000; i++) {
list.add(UUID.randomUUID().toString().replace("-", ""));
}
long start = System.currentTimeMillis();
Connection conn = jdbcUtils.connect();
String sql = "insert into a(id, name) VALUES (?,?)";
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
conn.setAutoCommit(false);//取消自动提交
for (int i = 0; i < list.size(); i++) {
ps.setObject(1, i);
ps.setObject(2, i);
ps.addBatch();
if (i % 500 == 0) {
ps.executeBatch();
ps.clearBatch();
}
}
ps.executeBatch();
ps.clearBatch();
conn.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
System.out.println("一百万条数据插入用时:" + (System.currentTimeMillis() - start) / 1000 + "【单位:秒】");
}
3.连接配置
jdbc:mysql://localhost:3306/activity?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT&rewriteBatchedStatements=true
4.效果