ITeye博客

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

luyao123127 · 2010-11-25 16:20 · Mysql · 数据库 · Java · SQL · MySQL · Markdown

第一种方式

数据库备份: 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*)){ 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)

暂无评论。

评论功能维护中,当前仅展示历史评论。