概述
public class TestJDBC {
private static long COUNT = 1000000;
private static long BATCH_SIZE = 20000;
private static long COMMIT_SIZE = 100000;
public static Connection getConnection() {
Connection conn = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "root";
try {
// 1 加载驱动程序
Class.forName(driver);
// 2 连接数据库
conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public void insertTest() {
Connection conn = null;
PreparedStatement pstat = null;
String sql = "insert into users values(?,?)";
try {
conn = getConnection();
conn.setAutoCommit(false);
pstat = conn.prepareStatement(sql);
for (int i = 0; i < COUNT; i += BATCH_SIZE) {
pstat.clearBatch();
for (int j = 0; j < BATCH_SIZE; j++) {
pstat.setInt(1, i + j);
pstat.setString(2, "a" + (i + j));
pstat.addBatch();// 使用batch()
}
pstat.executeBatch();
if ((i + BATCH_SIZE - 1) % COMMIT_SIZE == 0) {
conn.commit();
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 释放资源
}
}
}
最后
以上就是平淡母鸡为你收集整理的jdbc批量插入百万条数据的全部内容,希望文章能够帮你解决jdbc批量插入百万条数据所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复