案例代碼:
數據庫備份
1 //mysqldump -h端口號 -u用戶 -p密碼 數據庫 > d:/test.sql --備份D盤 2 //備份 3 public static void dataBaseDump(String port,String username,String password,String databasename,String sqlname) throws Exception { 4 File file = new File("F:\\test"); 5 if ( !file.exists() ){ 6 file.mkdir(); 7 } 8 File datafile = new File(file+File.separator+sqlname+".sql"); 9 if( datafile.exists() ){ 10 System.out.println(sqlname+"文件名已存在,請更換"); 11 return ; 12 } 13 //拼接cmd命令 14 Process exec = Runtime.getRuntime().exec("cmd /c mysqldump -h"+port+" -u "+username+" -p"+password+" "+databasename+" > "+datafile); 15 if( exec.waitFor() == 0){ 16 System.out.println("數據庫備份成功,備份路徑為:"+datafile); 17 } 18 }
數據庫還原
//還原 //mysql -h端口號 -u用戶 -p密碼 數據庫 < d:/test.sql 恢復到數據庫中 public static void backup(String port,String username,String password,String databasename,String sqlname) throws Exception { File datafile = new File("F:\\test\\"+sqlname+".sql"); if( !datafile.exists() ){ System.out.println(sqlname+"文件不已存在,請檢查"); return ; } //拼接cmd命令 Process exec = Runtime.getRuntime().exec("cmd /c mysql -h"+port+" -u "+username+" -p"+password+" "+databasename+" < "+datafile); if( exec.waitFor() == 0){ System.out.println("數據庫還原成功,還原的文件為:"+datafile); } }