對於千萬級表的清理有三種辦法;
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; } }