天天看點

java實作mysql資料庫備份與還原,簡單易用這裡直接上代碼了,應該都能看懂:

這裡直接上代碼了,應該都能看懂:

//用于備份的cmd指令:mysqldump -hIP位址 -u使用者 -p密碼 資料庫 表 > F:/home/publicApp.sql --備份到F盤
	 /*
	 方法參數:
		port:資料庫IP(例:192.168.1.1) 不用加端口号
		username:資料庫賬号(例:root)
		password:資料庫密碼(例:123456)
		databasename:資料庫名稱(例:public_app)
		tabname:資料庫表名稱(例:""或" sys_user")
		filePath:備份檔案存放路徑(例:F:/home) 
		sqlname:備份檔案名稱(例:publicApp)
		注:tabname為可選參數
				1.整庫備份時該參數設定為空字元串即可:""
				2.備份資料庫中指定的表時,參數為表名稱,注意表名稱前加空格:" sys_user"
				3.多張表之間空格連接配接即可:" sys_user sys_role sys_menu"
	 */

     //備份到指定路徑下
     public static void dataBaseCopy(String port,String username,String password,String databasename,String tabname,String filePath,String sqlname) {
         File file = new File(filePath);
         if ( !file.exists() ){
             file.mkdir();
         }
         File datafile = new File(file+File.separator+sqlname+".sql");
         if( datafile.exists() ){
             System.out.println(sqlname+"檔案名已存在,請更換檔案名!");
             return ;
         }
		try {
			//拼接cmd指令
			Process exec = Runtime.getRuntime().exec("cmd /c mysqldump -h"+port+" -u"+username+" -p"+password+" "+databasename+tabname+" > "+datafile);
            //exec.waitFor() 傳回0為成功,其他值為失敗。
            //一般失敗原因:1.參數錯誤 2.賬号密碼錯誤 3.檔案路徑錯誤
			if( exec.waitFor() == 0){
				log.info("資料庫備份成功,備份路徑為:"+datafile);
			}
		} catch (IOException | InterruptedException e) {
			log.info("資料庫備份失敗,執行cmd指令出錯!");
		}

     }	

	//恢複到資料庫中
	 public static void dataBaseRegain(String port,String username,String password,String databasename,String filePath,String sqlname) {
		 File datafile = new File(filePath+File.separator+sqlname+".sql");
		 if( !datafile.exists() ){
			 System.out.println(sqlname+"檔案不存在,請檢查檔案路徑是否正确!");
			 return ;
		 }
		 try {
			//拼接cmd指令
			Process exec = Runtime.getRuntime().exec("cmd /c mysql -h"+port+" -u"+username+" -p"+password+" "+databasename+" < "+datafile);
			if( exec.waitFor() == 0){
				log.info("資料庫還原成功,還原檔案為:"+datafile);
			}
		 } catch (IOException | InterruptedException e) {
			log.info("資料庫還原成功,執行cmd指令出錯!");
		 }
     }	
           

如果看不懂上邊的代碼,或者有其他問題,請留言,或加vx:mengzhaojie0713