Implement MySQL database backup in Java
After work, I will take my spare time to summarize how to back up MySQL databases using Java:
Import java. io. bufferedReader; import java. io. file; import java. io. fileOutputStream; import java. io. IOException; import java. io. inputStreamReader; import java. io. outputStreamWriter; import java. io. printWriter; /*** MySQL database backup *** @ author GaoHuanjie */public class MySQLDatabaseBackup {/*** Java code for MySQL Database Export ** @ author GaoHuanjie * @ param hostIP MySQL database server IP Address * @ param userName the userName required to enter the database * @ param UserName: userName required to enter the database * @ param password the password required to enter the database * @ param savePath Database Export File Storage path * @ param fileName Database Export File name * @ param databaseName to export database name * @ return returns true, indicating that the export is successful, otherwise, false is returned. */Public static boolean exportDatabaseTool (String hostIP, String userName, String password, String savePath, String fileName, String databaseName) throws InterruptedException {File saveFile = new File (savePath); if (! SaveFile. exists () {// if the directory does not exist, saveFile. mkdirs (); // create a folder} if (! SavePath. endsWith (File. separator) {savePath = savePath + File. separator;} PrintWriter printWriter = null; BufferedReader bufferedReader = null; try {printWriter = new PrintWriter (new OutputStreamWriter (new FileOutputStream (savePath + fileName), "utf8 ")); process process = runtime.getruntime(cmd.exe c ("mysqldump-h" + hostIP + "-u" + userName + "-p" + password + "-- set-charset = UTF8" + databaseName ); in PutStreamReader inputStreamReader = new InputStreamReader (process. getInputStream (), "utf8"); bufferedReader = new BufferedReader (inputStreamReader); String line; while (line = bufferedReader. readLine ())! = Null) {printWriter. println (line) ;}printwriter. flush (); if (process. waitFor () = 0) {// 0 indicates that the thread is terminated normally. Return true ;}} catch (IOException e) {e. printStackTrace () ;}finally {try {if (bufferedReader! = Null) {bufferedReader. close ();} if (printWriter! = Null) {printWriter. close () ;}} catch (IOException e) {e. printStackTrace () ;}} return false;} public static void main (String [] args) {try {if (exportDatabaseTool ("172.16.0.127", "root", "123456 ", "D:/backupDatabase", "2014-10-14. SQL", "test") {System. out. println ("the database is backed up successfully !!! ");} Else {System. out. println (" database backup failed !!! ") ;}} Catch (InterruptedException e) {e. printStackTrace ();}}}