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

11 篇文章 1 订阅

第一步 #  掌握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"))


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值