1.创建数据库备份工具类BackupDatabase
import java.io.File;
public class BackupDatabase {
public static int dataBaseDump(String port,String username,String password,String databasename,String sqlname,String fileUrl) throws Exception {
File file = new File(fileUrl);
if ( !file.exists() ){
file.mkdir();
}
File datafile = new File(file+ File.separator+sqlname+".sql");
if( datafile.exists() ){
System.out.println(sqlname+"文件名已存在,请更换");
return 1;
}
Process exec = Runtime.getRuntime().exec("cmd /c mysqldump -h"+port+" -u "+username+" -p"+password+" "+databasename+" > "+datafile);
if( exec.waitFor() == 0){
System.out.println("数据库备份成功,备份路径为:"+datafile);
return 0;
}else{
return 2;
}
}
}
2.编写测试类调用工具类实现数据库备份
@Test
public void dataBackup() throws Exception {
String startTime = DateUtils.getCurentTime();
System.out.println("-----------数据库备份开始,当前时间为=="+ startTime);
ResourceBundle bundle = ResourceBundle.getBundle("config");
String port = bundle.getString("jdbc.ip");
String databaseName = bundle.getString("jdbc.databaseName");
String username = bundle.getString("jdbc.username");
String password = bundle.getString("jdbc.password");
if(password.length()==88){
String publicKey = bundle.getString("jdbc.publicKey");
password = com.alibaba.druid.filter.config.ConfigTools.decrypt(publicKey,password);
}
String fileUrl = bundle.getString("jdbc.backupURL");
String sqlName = databaseName+"_" + DateUtils.getDateTimeNum();
int i = BackupDatabase.dataBaseDump(port, username, password, databaseName, sqlName, fileUrl);
if(i==0){
System.out.println("-----------数据库备份成功,当前时间为=="+ DateUtils.getCurentTime());
}else if(i==1){
System.out.println("-----------数据库备份失败,文件名已存在,请更换,当前时间为=="+ DateUtils.getCurentTime());
}else if(i==2){
System.out.println("-----------数据库备份失败,数据库连接异常,当前时间为=="+ DateUtils.getCurentTime());
}
}
3.本人的数据库配置文件config.properties如下
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
#数据库备份路径、数据库连接、数据库名称
jdbc.backupURL=D:/dataBackup
jdbc.ip=localhost
jdbc.databaseName=test
jdbc.username=root
#这里的数据库连接密码通过druid进行了加密
jdbc.password=HPHo1lGZU1Q+xjQCtqe1YAbIUsWMSrEw4AFEM+K7tnyQHCJCz/CJcqiKpsXu04ryyD6s940L73xHRpe5pOpkxQ==
jdbc.publicKey=MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJYS3Zzw2K7p8g5yhc7NqgrX5GkHYtdTU90+M0fT4zTjudMkco2t1NW2WACeFB1blzwRlk4M3kXJ90eHQpNGRAECAwEAAQ==
#定义初始连接数
jdbc.initialSize=0
#定义最大连接数
jdbc.maxActive=20
#定义最大空闲
jdbc.maxIdle=20
#定义最小空闲
jdbc.minIdle=1
#定义最长等待时间
jdbc.maxWait=600000