对于千万级表的清理有三种办法;
1.drop table 表名:用来删除表对象 。风险较大,后续不再使用,可以使用该方法。
2.truncate table 表名:清空表中所有数据,表结构还存在。所有数据不再使用,可以使用该方法
3.对于表结构不能删除,且只是按照条件删除表中某个条件数据,建议使用如下方法。高效删除数据,且不会删除其他条件数据。自动循环查询删除。
import java.sql.*;
import java.util.Date;
/**
* @Author BlueFire
* @Date 2020/4/17 -22:13
*/
public class InsertTest {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
final String url = "jdbc:mysql://127.0.0.1:3306/mooding?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
final String name = "com.mysql.jdbc.Driver";
final String user = "root";
final String password = "123456";
Connection conn = null;
Class.forName(name); //指定连接类型
conn = DriverManager.getConnection(url, user, password); //获取连接
if (conn != null) {
System.out.println("获取连接成功");
deleteBatch(conn);//批量删除数据
} else {
System.out.println("获取连接失败");
}
conn.close();
}
//批量删除 千万条数据
public static void deleteBatch(Connection conn) throws SQLException {
//数据中需要删除的数据量
Long expiredCount = 0L;
//已经删除数据量
Long totalDeleted = 0L;
//要删除表的名字
String table = "t_users";
//要删除的条件
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.setString(1, table);
pstmt.setString(2, schoolName);
// 返回值代表收到影响的行数
int result = pstmt.executeUpdate();
//已经删除条数
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.setString(1, table);
pstmt.setString(2, schoolName);
ResultSet rs = pstmt.executeQuery(sql);
while (rs.next()) {
long count = rs.getInt("cnt");
return count;
}
return 0L;
}
}
导入千万级数据方法可参考下文