【MySQL】批量清空MySQL数据表,主键自增从1开始

小破孩
2025-03-25 / 0 评论 / 19 阅读 / 正在检测是否收录...
    public function truncateTables()
    {
        // 要排除的表
        $exclude_tables = [
            'web_admin_func',// 权限表
            'web_admin_role',// 角色表
            'web_admin_user',// 用户表
            'web_china_city',// 中国行政区划表
            'web_china_city_area',// 四级省市区镇地区表
            'web_china_city_backup',// 中国行政区划表初始备份
        ];

        try {
            // 开启事务
            Db::startTrans();

            // 获取所有表名
            $tables = Db::query('SHOW TABLES');

            foreach ($tables as $table) {
                $table_name = current($table);
                if (!in_array($table_name, $exclude_tables)) {
                    // 清空表并重置索引
                    Db::execute("TRUNCATE TABLE {$table_name}");
                    echo "表 {$table_name} 已清空<br>";
                }
            }

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            echo "发生错误: " . $e->getMessage();
        }
    }
0

评论 (0)

取消