此时情绪此时天,无事小神仙
好好生活,平平淡淡每一天

编辑

备份Mysql数据库数据工具类

Java代码

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.jfinal.plugin.activerecord.Db;

import net.wwwyibu.jfinal.config.DataLoad;

/**
 * @author 马家立
 * @version 创建时间:2019年12月12日下午3:49:35
 * @Description: 备份Mysql数据库数据工具类
 */
public class BackupsUtil {

    private static final Logger logger = Logger.getLogger(BackupsUtil.class);

    /**
     * @Title:createDBByName
     * @author:马家立
     * @date:2019年12月12日 下午3:57:55
     * @Description: 根据数据库名称创建数据库
     * @param dbName--数据库名称
     * @return boolean--true:创建成功;false:创建失败
     */
    public static boolean createDBByName(String dbName) {
        logger.info("进入BackupsUtil的createDBByName方法");
        try {
            // 保存创建数据库的sql
            StringBuffer creatDBSql = new StringBuffer();
            creatDBSql.append("create database if not exists " + dbName + " ");
            // 设置字符集
            creatDBSql.append("default character set gbk ");
            // 设置字符集默认校对规则
            creatDBSql.append("default collate gbk_chinese_ci ");
            // 执行sql并接收受影响的行数
            Db.update(creatDBSql.toString());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("BackupsUtil的createDBByName error", e);
        }
        return false;
    }

    /**
     * @Title:backUpDbToOneTable
     * @author:马家立
     * @date:2019年12月12日 下午5:15:27
     * @Description: 备份旧数据库里面的一张表
     * @param oldDbName--需要备份的数据库
     * @param newsDbName--备份到指定的数据库,如果没有则创建新数据库
     * @param tableName--需要备份的表名
     *            void
     * @throws Exception
     */
    public static void backUpDbToOneTable(String oldDbName, String newsDbName, String tableName) throws Exception {
        logger.info("进入BackupsUtil的backUpDbToOneTable方法");
        List<String> sqlList = new ArrayList<String>();
        // 在数据库db2中建立一个和db1中一样的表table
        sqlList
            .add("create table if not exists " + newsDbName + "." + tableName + " LIKE " + oldDbName + "." + tableName);
        // 清空表中的数据
        sqlList.add("truncate table " + newsDbName + "." + tableName);
        // 将数据库db1.table1 复制到 数据库db2.table2
        sqlList.add("insert into " + newsDbName + "." + tableName + " select * from " + oldDbName + "." + tableName);
        Db.batch(sqlList, 3);
        logger.info("备份成功的表:" + tableName);
    }

    /**
     * @Title:findTablesByDbName
     * @author:马家立
     * @date:2019年12月12日 下午3:51:33
     * @Description: 根据数据库名获取所有的表名
     * @param dbName--数据库名字
     * @return List<String>
     * @throws Exception
     */
    public static List<String> findTablesByDbName(String dbName) throws Exception {
        logger.info("进入BackupsUtil的findTablesByDbName方法");
        if (QwyUtil.isNullAndEmpty(dbName)) {
            logger.error("数据库名为空");
            return null;
        }
        String sql = "SELECT table_name FROM information_schema.TABLES WHERE TABLE_SCHEMA= ? ";
        List<String> params = new ArrayList<String>();
        params.add(dbName);
        // 查询出所有的表名
        params = Db.query(sql, params.toArray());
        return params;
    }

    /**
     * @Title:backUpDbTable
     * @author:马家立
     * @date:2019年12月13日 下午2:03:47
     * @Description: 把旧数据库的表数据备份到新数据库里面
     * @param oldDbName--旧数据库名称
     * @param newsDbName--新数据库名称
     * @param tables--旧数据库的表数据集合
     * @return Map<String,String>{code:ok或者err;msg:错误信息,如果为空则无错误信息,count:成功的数量}
     */
    public static Map<String, String> backUpDbTable(String oldDbName, String newsDbName, List<String> tables) {
        logger.info("进入BackupsUtil的backUpDbTable方法");
        Map<String, String> resultMap = new HashMap<String, String>();
        try {
            resultMap.put("code", "ok");
            if (QwyUtil.isNullAndEmpty(oldDbName)) {
                logger.error("旧数据库名为空");
                resultMap.put("code", "err");
                resultMap.put("msg", "旧数据库名为空");
                return resultMap;
            }
            if (QwyUtil.isNullAndEmpty(newsDbName)) {
                logger.error("新数据库名为空");
                resultMap.put("code", "err");
                resultMap.put("msg", "新数据库名为空");
                return resultMap;
            }
            // 根据数据库名称创建数据库
            boolean iscreateDBOk = createDBByName(newsDbName);
            if (!iscreateDBOk) {
                logger.error("创建新数据库失败");
                resultMap.put("code", "err");
                resultMap.put("msg", "创建新数据库失败");
                return resultMap;
            }
            if (QwyUtil.isNullAndEmpty(tables)) {
                logger.info("需要备份的表为空");
                resultMap.put("code", "err");
                resultMap.put("msg", "需要备份的表为空");
                return resultMap;
            }
            // 表数量
            int counts = 0;
            for (String table : tables) {
                // 判断字符串中是否包含数字
                // if (hasDigit(table)) {
                // continue;
                // }
                backUpDbToOneTable(oldDbName, newsDbName, table);
                System.out.println("备份成功的表:" + table);
                logger.info("备份成功的表:" + table);
                counts++;
            }
            resultMap.put("counts", counts + "");
        } catch (Exception e) {
            resultMap.put("code", "err");
            resultMap.put("msg", "备份数据表方法异常");
            e.printStackTrace();
            logger.error("备份数据表方法异常", e);
        }
        return resultMap;
    }

    /**
     * @Title:findToTableBegin
     * @author:马家立
     * @date:2019年12月13日 下午2:20:02
     * @Description: 在数据库中查找以XXX字符串开头的表
     * @param dbName--数据库名
     * @param prefixTable--以XXX开头的字符串
     * @param flag--true:以XXX开头;false:不以XXX开头
     * @return List<String>--null:则是参数为空或者异常
     * @throws Exception
     */
    public static List<String> findToTableBegin(String dbName, String prefixTable, boolean flag)
        throws Exception {
        logger.info("进入BackupsUtil的findToTableBegin方法");
        if (QwyUtil.isNullAndEmpty(dbName)) {
            logger.error("旧数据库名为空");
            return null;
        }
        if (QwyUtil.isNullAndEmpty(prefixTable)) {
            logger.error("参数前缀为空");
            return null;
        }
        // 根据数据库名获取所有的表名
        List<String> allTables = findTablesByDbName(dbName);
        if (QwyUtil.isNullAndEmpty(allTables)) {
            logger.error("数据库下无表存在!");
            return null;
        }
        // 需要备份的表
        List<String> newstables = new ArrayList<String>();
        // 遍历添加所需备份的表
        for (String table : allTables) {
            if (flag) {
                // 以它开头的表
                if (table.startsWith(prefixTable)) {
                    newstables.add(table);
                }
            } else {
                // 不以它开头的表
                if (!table.startsWith(prefixTable)) {
                    newstables.add(table);
                }
            }
        }
        return newstables;
    }

    /**
     * @Title:findToTableEnd
     * @author:马家立
     * @date:2019年12月13日 下午2:21:02
     * @Description: 在数据库中查找以XXX字符串结尾的表
     * @param dbName--数据库名
     * @param suffixTable--以XXX结尾的字符串
     * @param flag--true:以XXX结尾;false:不以XXX结尾
     * @return List<String>--null:则是参数为空或者异常
     * @throws Exception
     */
    public static List<String> findToTableEnd(String dbName, String suffixTable, boolean flag) throws Exception {
        logger.info("进入BackupsUtil的findToTableEnd方法");
        if (QwyUtil.isNullAndEmpty(dbName)) {
            logger.error("旧数据库名为空");
            return null;
        }
        if (QwyUtil.isNullAndEmpty(suffixTable)) {
            logger.error("参数后缀为空");
            return null;
        }
        // 根据数据库名获取所有的表名
        List<String> allTables = findTablesByDbName(dbName);
        if (QwyUtil.isNullAndEmpty(allTables)) {
            logger.error("数据库下无表存在!");
            return null;
        }
        // 需要备份的表
        List<String> newstables = new ArrayList<String>();
        // 遍历添加所需备份的表
        for (String table : allTables) {
            if (flag) {
                // 以它结尾的表
                if (table.endsWith(suffixTable)) {
                    newstables.add(table);
                }
            } else {
                // 不以它结尾的表
                if (!table.endsWith(suffixTable)) {
                    newstables.add(table);
                }
            }
        }
        return newstables;
    }

    /**
     * @Title:findToTableContain
     * @author:马家立
     * @date:2019年12月13日 下午2:23:02
     * @Description: 在数据库中查找包含xxx字符串的表
     * @param dbName--数据库名
     * @param containTable--包含XXX的字符串
     * @param flag--true:数据库包含XXX的表名,false:数据库不包含XXX的表名
     * @return List<String>--null:则是参数为空或者异常
     * @throws Exception
     */
    public static List<String> findToTableContain(String dbName, String containTable, boolean flag) throws Exception {
        logger.info("进入BackupsUtil的findToTableContain方法");
        if (QwyUtil.isNullAndEmpty(dbName)) {
            logger.error("旧数据库名为空");
            return null;
        }
        if (QwyUtil.isNullAndEmpty(containTable)) {
            logger.error("参数包含为空");
            return null;
        }
        // 根据数据库名获取所有的表名
        List<String> allTables = findTablesByDbName(dbName);
        if (QwyUtil.isNullAndEmpty(allTables)) {
            logger.error("数据库下无表存在!");
            return null;
        }
        // 需要备份的表
        List<String> newstables = new ArrayList<String>();
        // 遍历添加所需备份的表
        for (String table : allTables) {
            if (flag) {
                // 包含什么的表
                if (-1 != table.indexOf(containTable)) {
                    newstables.add(table);
                }
            } else {
                // 不包含什么的表
                if (-1 == table.indexOf(containTable)) {
                    newstables.add(table);
                }
            }
        }
        return newstables;
    }


    /**
     * @Title:hasDigit
     * @author:马家立
     * @date:2019年12月12日 下午3:59:47
     * @Description: 判断字符串中是否包含数字
     * @param str--字符串
     * @return boolean--true:包含数字,false:不包含数字
     * @throws Exception
     */
    public static boolean hasDigit(String str) throws Exception {
        logger.info("进入BackupsUtil的hasDigit方法");
        boolean flag = false;
        Pattern p = Pattern.compile(".*\\d+.*");
        Matcher m = p.matcher(str);
        if (m.matches()) {
            flag = true;
        }
        return flag;
    }

    public static void main(String[] args) {
        try {
            DataLoad.startOA();
            String oldDbName = "schooloadb_20190128";
            String newsDbName = "schooloadb_20190128_tabu";
            // /根据数据库名获取所有的表名
            List<String> tables = findTablesByDbName(oldDbName);
            System.out.println("库中表集合数量为:" + tables.size());
            // 待备份的表集合
            List<String> bfTables = new ArrayList<String>();
            for (String table : tables) {
                if (table.contains("2016") || table.contains("2017") || table.contains("2018") || table.contains("2019")
                    || table.contains("bk") || table.contains("bf") || table.contains("copy")) {
                    continue;
                } else {
                    bfTables.add(table);
                    System.out.println("待备份的表名:" + table);
                }
            }
            System.out.println("待备份的表集合数量为:" + bfTables.size());
            // 把旧数据库的表数据备份到新数据库里面
            Map<String, String> resultMap = backUpDbTable(oldDbName, newsDbName, bfTables);
            System.out.println(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
posted @ 2019-12-13 14:54  踏步  阅读(242)  评论(0编辑  收藏  举报