Java代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* @author LeDao
* @company
* @create 2021-04-23 21:39
*/
public class Backup {

/**
* 数据库用户名
*/
private String user_name;
/**
* 数据库密码
*/
private String user_psw;
/**
* 需要备份的数据库名
*/
private String db_name;
/**
* 主机IP
*/
private String host_ip;
/**
* 字符集
*/
private String user_charset;
/**
* 存放备份文件的路径
*/
private String backup_path;
/**
* 命令
*/
private String stmt;

public Backup(String user_name, String user_psw, String db_name,
String host_ip, String user_charset, String backup_path) {
this.user_name = user_name;
this.user_psw = user_psw;
this.db_name = db_name;
// 主机IP;
if (host_ip == null || host_ip.equals("")) {
// 默认为本机
this.host_ip = "localhost";
} else {
this.host_ip = host_ip;
}
// 字符集
if (user_charset == null || user_charset.equals("")) {
// 默认为安装时设置的字符集
this.user_charset = " ";
} else {
this.user_charset = " --default-character-set=" + user_charset;
}
this.backup_path = backup_path;
this.stmt = "C:\\Program Files\\MySQL\\MySQL Server 5.6\\bin\\mysqldump "
+ this.db_name + " -h " + this.host_ip + " -u" + this.user_name
+ " -p" + this.user_psw + this.user_charset + " --result-file="
+ this.backup_path;
}

public boolean backup_run() {
boolean run_result = false;
try {
Runtime.getRuntime().exec(this.stmt);
run_result = true;
} catch (Exception e) {
e.printStackTrace();
}
return run_result;
}

public static void main(String[] args) {
Backup backup = new Backup("root", "123456", "db_myblog", null, "utf8",
"D:\\db_backup\\db_myblog.sql");
boolean result = backup.backup_run();
if (result) {
System.out.println("备份成功");
}
}
}

结果

img

img