Java使用JDBC批量删除千万级数据

更新时间:2023-06-25 18:29:01 阅读: 评论:0

Java使⽤JDBC批量删除千万级数据
对于千万级表的清理有三种办法;
1.drop table 表名:⽤来删除表对象。风险较⼤,后续不再使⽤,可以使⽤该⽅法。
火影忍者封面2.truncate table 表名:清空表中所有数据,表结构还存在。所有数据不再使⽤,可以使⽤该⽅法酒水牌
3.对于表结构不能删除,且只是按照条件删除表中某个条件数据,建议使⽤如下⽅法。⾼效删除数据,且不会删除其他条件数据。⾃动循环查询删除。
import java.sql.*;
import java.util.Date;
/**
一缕清风* @Author BlueFire
* @Date 2020/4/17 -22:13
*/
public class InrtTest {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
final String url = "jdbc:mysql://127.0.0.1:3306/mooding?autoReconnect=true&uUnicode=true&characterEncoding=utf8&rverTimezone=Asia/Shanghai";
final String name = "sql.jdbc.Driver";
final String ur = "root";
final String password = "123456";
Connection conn = null;
Class.forName(name); //指定连接类型
conn = Connection(url, ur, password); //获取连接
if (conn != null) {
水天相接System.out.println("获取连接成功");
deleteBatch(conn);//批量删除数据
} el {
System.out.println("获取连接失败");
}
conn.clo();
}
//批量删除千万条数据
public static void deleteBatch(Connection conn) throws SQLException {
//数据中需要删除的数据量
Long expiredCount = 0L;
//已经删除数据量
Long totalDeleted = 0L;
//要删除表的名字
String table = "t_urs";
//要删除的条件
String schoolName = "XX⼤学";
// 开始时间
Long begin = new Date().getTime();
//带有占位符的sql
String sql = "delete from ? where school_name = ?    limit 100000 ";
PreparedStatement pstmt = conn.prepareStatement(sql);
//循环批量删除
do {
pstmt.tString(1, table);
pstmt.tString(2, schoolName);
// 返回值代表收到影响的⾏数手影舞
int result = uteUpdate();
//已经删除条数
totalDeleted += result;
//还有条数
expiredCount = queryCount(table, schoolName, conn);唐朝女人
} while (expiredCount > 0);
// 结束时间
Long end = new Date().getTime();
// 耗时
System.out.println("千万条数据删除花费时间 : " + (end - begin) / 1000 + " s");
陈瑞平System.out.println("删除完成");
}
//查询过期记录数量
private static long queryCount(String table, String schoolName, Connection conn) throws SQLException {
String sql = "SELECT COUNT (*) as cnt FROM  ?  where  school_name = ? ";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.tString(1, table);
pstmt.tString(2, schoolName);
爸爸的领带ResultSet rs = uteQuery(sql);
while (rs.next()) {
long count = rs.getInt("cnt");
return count;
}
return 0L;
} }

本文发布于:2023-06-25 18:29:01,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/82/1038130.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:删除   数据   条件   连接   批量   时间   获取
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图