Java程序调用系统命令进行mysql数据库的备份与还原(方式一)

第一种方式

数据库备份:
public class DBBackup {
//导出数据库成sql文件
public static void backup(String DBName,String file){

String user = "root"; // 数据库帐号
String password = "123456"; // 登陆密码
String database = DBName; // 需要备份的数据库名
String filepath = file; // 备份的路径地址
String Str="mysqldump " + database + " -u " + user + " -p"+ password + " --result-file=" + filepath;
try {
Process p=Runtime.getRuntime().exec(Str); //执行命令
p.waitFor(); //命令执行时,等待状态
System.out.println("数据已导出到文件" + filepath + "中");
}
catch (IOException e) {
e.printStackTrace();
}
catch(InterruptedException e){
e.printStackTrace();
}
}

}


数据恢复:
public class DBUpload {

private static String databases;//mysql中所有数据库的名称组成的字符串,逗号隔开
static{
QueryBuilder qb=new QueryBuilder("show databases;");
DataTable dt=qb.executeDataTable();
StringBuffer court=new StringBuffer("");
if(dt.getRowCount()>0){
for(int i=0;i<dt.getRowCount();i++){
if(i==0){
court.append(dt.getString(i,"Database"));
}else{
court.append(","+dt.getString(i,"Database"));
}
}
databases=court.toString().trim();
}else{
databases="";
}
}

//判断数据库是否已经存在
public static boolean isExist(String DBName){
if(StringUtil.isEmpty(databases)){
return false;
}else{
String dbs[]=databases.split(",");
for(int i=0;i<dbs.length;i++){
if(DBName.equalsIgnoreCase(dbs[i])){
return true;
}else{
continue;
}
}
return false;
}
}


//导入到数据库中
public static boolean load(String DBName,String file){
String user = "root"; // 数据库帐号
String password = "123456"; // 登陆密码
String database = DBName; // 需要备份的数据库名
String filepath=file;
String str1="mysqladmin -u "+user+" -p"+password+" create "+database;
String str2="mysql -u "+user+" -p"+password+" "+database+" < " + filepath;
String[] cmd={"cmd","/c",str2};
try{
if(!isExist(DBName)){//不存在此数据库
Runtime.getRuntime().exec(str1);
}
Process p= Runtime.getRuntime().exec(cmd);
p.waitFor();
System.out.println("数据已从 " + filepath + " 导入到数据库中");
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
}

}

QueryBuilder DataTable StringUtil均是经过封装的类
此方式不足之处在于,所有的路径中不能有空格,若有空格程序无法执行!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值