java代码执行数据库备份

直接上代码,  有main方法 直接测试就ok
package com.ofoShare.util;

import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;
import java.util.logging.SimpleFormatter;

import org.apache.struts2.ServletActionContext;

import com.sun.jndi.cosnaming.IiopUrl.Address;

public class BackDB {
	public static void main(String[] args) {
		exportDatabaseTool();
	}
	public static boolean exportDatabaseTool() {
		Properties properties = new Properties();
		try {
			properties.load(BackDB.class
					.getResourceAsStream("../../../jdbc.properties"));
		} catch (IOException e) {
			System.out.println("未找到配置文件!!!");
		}
		String username = properties.getProperty("jdbc.username");// 用户名
		String password = properties.getProperty("jdbc.password");// 用户密码
		String exportDatabaseName = properties.getProperty("jdbc.dbname");// 需要导出的数据库名
		String host = properties.getProperty("jdbc.host");// 从哪个主机导出数据库,如果没有指定这个值,则默认取localhost
		String port = properties.getProperty("jdbc.port");// 使用的端口号

		Format format = new SimpleDateFormat("yyyyMMddHHmmssSSS");

		String exportPath = "D:\\dbBack\\" + exportDatabaseName
				+ format.format(new Date()).toString() + ".sql";
		// + UUID.randomUUID().toString().replaceAll("-", "") + ".sql";// 导出路径

		// 注意哪些地方要空格,哪些不要空格
		// 密码是用的小p,而端口//是用的大P。
		StringBuffer command = new StringBuffer();
		command.append("mysqldump -u").append(username).append(" -p")
				.append(password).append(" -h").append(host).append(" -P")
				.append(port).append(" ").append(exportDatabaseName)
				.append(" -r ").append(exportPath);
		try {
			Process process = Runtime.getRuntime().exec(command.toString());
			if (process.waitFor() == 0) {// 0 表示线程正常终止。
				System.out.println("数据库备份成功!"+format.format(new Date()));
				return true;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return false;
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值