java 代码通过调用mysqldump命令备份mysql数据库
数据库备份是开发工作中经常要做的事情,好处是mysql提供了一个非常好的命令 mysqldump,直接调用它就可以将数据以sql文件的形式备份出来。但是直接写命令非常不方便,遇到定时备份或者指定备份那么就需要代码调用。下面是一个使用java代码调用该命令的小示例:
public CommonResult backupLoginfo(ConnectParam connectParam, boolean backupAll,
String startTime, String endTime) {
CommonResult result = new CommonResult();
String strFilter;
String strFilePath = strLogExcelPath;
if (backupAll) {
strFilter = "\"1=1\"";
strFilePath += String.format("loginfo-%s.dump", System.currentTimeMillis());
} else {
if (null == startTime || startTime.isEmpty() || null == endTime || endTime.isEmpty()) {
result.message = "起止时间不能为空";
result.result = false;
return result;
} else {
strFilter = String.format("\"OPERTIME BETWEEN '%s' AND '%s'\"", startTime, endTime);
strFilePath += String.format("loginfo(%s_%s).dump", startTime, endTime)
.replaceAll(":", "");
}
}
try {
int nBackUpResult = backUpDataTable(connectParam.ip,
connectParam.userName,
connectParam.password,
String.format(" %s lnd_loginfo", connectParam.databaseName),
strFilter,
strFilePath);
if (0 == nBackUpResult) {
result.result = true;
return result;
}
} catch (IOException ie) {
logger.error(ie.getMessage());
} catch (InterruptedException ire) {
logger.error(ire.getMessage());
} catch (Exception e) {
logger.error(e.getMessage());
}
result.result = false;
result.message = "备份异常";
return result;
}
public static int backUpDataTable(String clientIp, String userName, String userPsw,
String tableInfo, String strFilter, String strFilePath)
throws IOException, InterruptedException {
File file = new File(strFilePath).getParentFile();
if (!file.exists()) {
file.mkdirs();
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("mysqldump -t --opt -h").append(clientIp)
.append(" --user=").append(userName).append(" --password=").append(userPsw).append(tableInfo)
.append(" --where=").append(strFilter)
.append(" --lock-all-tables=true")
.append(" --result-file=").append(strFilePath).append(" --default-character-set=utf8");
logger.info("执行mysql指令:" + stringBuilder.toString());
Process process = Runtime.getRuntime().exec(stringBuilder.toString());
return process.waitFor();
}
其中backupLoginfo()方法是备份数据的调用方法,传入的参数是连接mysql的信息,类如下,可以备份某个数据库的表的全部数据或者选择一部分数据。这里通过参数backupAll来确定,当backupAll=true的时候,那么输入备份的时间。
public class ConnectParam {
public String ip;
public String databaseName;
public String userName;
public String password;
}