import java.io.*;
public class DataBackupService {
public static final String CMD = "mysqldump --databases -h%s -P%s -u%s -p%s %s";
/**
* 备份数据库 ,控制台执行命令格式
* mysql的bin目录/mysqldump --databases -h主机ip -P端口 -u用户名 -p密码 数据库名
*
* @param mysqlIp mysql主机ip
* @param mysqlPort 端口
* @param userName 用户名
* @param password 密码
* @param database 数据库名
*/
public void backup(String mysqlIp,
String mysqlPort,
String userName,
String password,
String database) {
try {
String cmd = String.format(CMD,mysqlIp,mysqlPort,userName,password,database);
Process process = Runtime.getRuntime().exec(cmd);
new InputStreamProcessor(process).start();
new ErrorInputStream(process).start();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
static class InputStreamProcessor extends Thread{
private final Process process;
private final String path = String.format("d:\\%s_wms_ts_test.sql",System.currentTimeMillis());
public InputStreamProcessor(Process process) {
this.process = process;
}
@Override
public void run() {
try (InputStream is = process.getInputStream();
FileOutputStream out = new FileOutputStream(path);){
byte[] b = new byte[1024];
int len = -1;
while ((len = is.read(b)) != -1) {
out.write(b, 0, len);
}
} catch (Exception e) {
throw new RuntimeException();
}
}
}
static class ErrorInputStream extends Thread{
private final Process process; // 控制台errorStream
private final String path = String.format("d:\\%s_error_wms_ts_test.sql",System.currentTimeMillis());
public ErrorInputStream(Process process) {
this.process = process;
}
@Override
public void run() {
try (InputStream is = process.getErrorStream();
FileOutputStream out = new FileOutputStream(path);){
byte[] b = new byte[1024];
int len = -1;
while ((len = is.read(b)) != -1) {
out.write(b, 0, len);
}
} catch (Exception e) {
throw new RuntimeException();
}
}
}
public static void main(String[] args) {
String mysqlIp = "127.0.0.1";
String mysqlPort = "3306";
String userName = "root";
String password = "root";
String database = "wms_ts_test";
DataBackupService service = new DataBackupService();
service.backup(mysqlIp,mysqlPort,userName,password,database);
}
}
mysql数据备份-java实现
于 2022-07-21 16:15:29 首次发布