直接上代码, 有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;
}
}