After work, use your spare time to summarize how to use the Java language for MySQL database backup:
[Java]View PlainCopy
- 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 Implementation MySQL database export
- *
- * @author Gaohuanjie
- * @param hostip MySQL database is located on the server address IP
- * @param userName User name required to enter the database
- * @param password The password required to enter the database
- * @param savepath Database Export File save path
- * @param filename Export file name of the filename database
- * @param databaseName The name of the database to be exported
- * @return returns True to indicate that the export was successful, otherwise false.
- */
- public Static boolean Exportdatabasetool (String HostIP, String userName, string password, string savepath, St Ring 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 (Newoutputstreamwriter (new FileOutputStream (Savepath + fileName), "UTF8" ));
- Process process = Runtime.getruntime (). EXEC ("mysqldump-h" + HostIP + "-u" + userName + "-P" + Password + " c3> "--set-charset=utf8" + databaseName);
- InputStreamReader 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 normal termination of the thread.
- 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 ("database successfully backed up!!! ");
- } Else {
- SYSTEM.OUT.PRINTLN ("Database backup failed!!! ");
- }
- } catch (Interruptedexception e) {
- E.printstacktrace ();
- }
- }
- }
Java implementation MySQL database backup (i)