mysql数据库备份 java定时备份数据库

第一步 #  掌握sql备份语句

指定数据库:

         mysqldump  -h 数据库ip -u 用户名 -p --databases 数据库名称 --set-gtid-purged=off>/home/test.sql

指定数据库的某表:

        mysqldump  -h 数据库ip -u 用户名 -p --databases 数据库名 表名 --set-gtid-purged=off>/home/test.sql

示例:

         mysqldump  -h 127.0.0.1  -u root  -p  zhiye area >D:\test\tes.sql


第二步 #  写一个执行 mysqldump sql 语句的java工具类

    以下是备份工具类MySQLBacupUtil

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zhiyeit.controllerm.MAuthenticationController;

public class MysqlBackupUtil {
	static final Logger log = LoggerFactory.getLogger(MAuthenticationController.class);
	public static boolean  backupData(String host,String dbName,String account,String pass,String savaPath){
		Long starttime=System.currentTimeMillis();
		Runtime rt=Runtime.getRuntime();
		Process process;
		try {
			String command="mysqldump -h "+host+" -u "+account+" -p"+pass+" "+dbName+" --result-file "+savaPath+DateUtil.getDate(null, new Date())+".sql";
			log.info("mysqldump running this comman-->"+command);
			process = rt.exec(command);
			if(process.waitFor()==0){
				log.info("mysqldump backup successfully");
				Long endtime=System.currentTimeMillis();
				Long distance=starttime-endtime;
				log.info("mysqldump备份花"+distance/1000+"秒");
				return true;
				
			}else{
				log.info("process.waitFor()!=0");
				InputStream is=process.getErrorStream();
				if(is!=null){
					BufferedReader in=new BufferedReader(new  InputStreamReader(is,"utf-8"));
					String line;
					while((line=in.readLine())!=null){
						log.error("mysqldump错误日志>"+line);
					}
				}
			}
		}catch (Exception e) {
			log.info("mysqldump backup failed");
			e.printStackTrace();
			return false;
		}
		return false;
		
	}
	
}

第三步 #       在定时任务中直接执行写好的备份工具类 MySQLBackupUtil

MysqlBackupUtil.backupData(Config.get("host"),Config.get("dbName"), Config.get("account"),  Config.get("pass"),  Config.get("savaPath"))


猜你喜欢

转载自blog.csdn.net/weixin_38570967/article/details/80150204