Java implementation MySQL database automatic backup

Source: Internet
Author: User
Tags mysql host terminates mysql backup

One such requirement in recent projects requires that the database be backed up regularly. Read some online information, understand the main idea is to use the Java Runtime Class exec () method, you can directly invoke the Windows cmd command, the parameters are MySQL backup command.

First, the runtime class

First of all, this magical runtime class, mainly encapsulates the Java program's operating environment, each Java program has a corresponding runtime instance, the application through the object and the runtime environment, the application cannot create its own runtime instance, However, the runtime object associated with it can be obtained through the GetRuntime () method.

runtime represents the runtime environment of a Java program and can access information about the JVM, such as the number of processors and memory information.

1.1. Common API

     Addshutdownhook (Thread hook)
Register a new virtual machine to close the hook.
availableprocessors ()
Returns the number of available processors to the Java virtual machine.
exec (String command)
Executes the specified string command in a separate process.
exec (string[] cmdarray)
Executes the specified commands and variables in a separate process.
exec (string[] cmdarray, string[] envp)
Executes the specified command and variable in a separate process for the specified environment.
exec (string[] cmdarray, string[] envp, File dir)
Executes the specified commands and variables in a separate process that specifies the environment and working directory.
exec (String command, string[] envp)
Executes the specified string command in a separate process in the specified environment.
exec (String command, string[] envp, File dir)
Executes the specified string command in a separate process with the specified environment and working directory.
exit (int status)
Terminates the currently running Java virtual machine by starting the shutdown sequence of the virtual machine.
freememory ()
Returns the amount of idle memory in a Java virtual machine.
GC ()
Run the garbage collector.
InputStream Getlocalizedinputstream (InputStream in)
is obsolete. Starting with JDK 1.1, the preferred way to convert a local coded byte stream to a Unicode character stream is to use the InputStreamReader and BufferedReader classes.
OutputStream Getlocalizedoutputstream (OutputStream out)
is obsolete. Starting with JDK 1.1, the preferred way to convert a stream of Unicode characters to a local coded byte stream is to use the OutputStreamWriter, BufferedWriter, and PrintWriter classes.
GetRuntime ()
Returns the run-time object associated with the current Java application.
Halt (int status)
Forcibly terminates the currently running Java virtual machine.
load (String filename)
Loads the specified file name as a dynamic library.
loadLibrary (String libname)
Loads a dynamic library with the specified library name.
MaxMemory ()
Returns the maximum amount of memory that the Java virtual machine is attempting to use.
Removeshutdownhook (Thread hook)
Unregister a previously registered virtual institution closed hook.
runfinalization ()
The terminating method for all objects that are running pending finalization.
Runfinalizersonexit (value)
is obsolete. This method itself has no security. It may invoke the finalization method on the object being used, while other threads are manipulating these objects, resulting in improper behavior or deadlock.
totalmemory ()
Returns the total amount of memory in the Java virtual machine.
traceinstructions (ON)
Enable/disable command tracking.
Tracemethodcalls (ON)
Enables/disables method call tracing.

1.2. Use the exec (String cmd) method to back up the database

Databasetool class

 PackageCom.china_amss.base.tools;ImportJava.io.BufferedReader;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.OutputStreamWriter;ImportCom.china_amss.base.thread.ErrorStreamThread; Public classDatabasetool {/*** Backup database, console execution command format "MySQL bin directory/mysqldump--databases-h host ip-p Port-u user name-p password--default-character-set= character set database name * @parammysqlpath MySQL Path *@parammysqlip mysql Host IP *@paramMysqlport Port *@paramuserName User name *@paramPassword Password *@paramCharSet Character Set *@paramDatabase name *@paramresultfile backup file full path*/     Public Static voidBackup (String Mysqlpath, String mysqlip, String mysqlport, String userName, string password, string database, Stri ng Resultfile) {InputStream in=NULL; InputStreamReader ISR=NULL; BufferedReader BR=NULL; FileOutputStream Fout=NULL; OutputStreamWriter writer=NULL; Try{Runtime rt=Runtime.getruntime (); //command to call the MySQL installation directoryProcess process = rt.exec ("\" "+ Mysqlpath + file.separator +" mysqldump\ "--databases-h" + mysqlip
+ "-P" +Mysqlport+ "-U" + userName + "-P" +Password+ "--add-drop-database--default-character-set=utf8" + database + "--result-file=" +resultfile); //set the export encoding to Utf-8. This must be Utf-8 .in = Process.getinputstream ();//output information for the console as an input streamErrorstreamthread Errstream =NewErrorstreamthread (Process.geterrorstream ());//error stream Another thread, or it will blockErrstream.start (); } Catch(Exception e) {e.printstacktrace (); }        finally{            Try {                if(Writer! =NULL) {writer.close (); }                if(Fout! =NULL) {fout.close (); }                if(BR! =NULL) {br.close (); }                if(ISR! =NULL) {isr.close (); }                if(In! =NULL) {in.close (); }            } Catch(IOException e) {e.printstacktrace (); }        }    }

Errorstreamthread class:

 PackageCom.china_amss.base.thread;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;Importcom.china_amss.ktms.exception.KTMSException; Public classErrorstreamthreadextendsThread {PrivateInputStream input;//Console Errorstream     Publicerrorstreamthread (InputStream input) { This. Input =input; } @Override Public voidrun () {InputStreamReader ISR=NULL; BufferedReader Buff=NULL; Try{ISR=NewInputStreamReader (input); Buff=NewBufferedReader (ISR);            String Line;  while(line = Buff.readline ())! =NULL) {                if(Line.indexof ("Warning")! = 0) {                    Throw NewException (line); }            }        } Catch(Exception e) {Throw NewException ("Error thread method Exception", E); } finally {            Try {                if(Buff! =NULL) {buff.close (); }                if(ISR! =NULL) {isr.close (); }            } Catch(IOException e) {Throw NewException ("Error thread method Exception", E); }        }    }}

Note: This is because you want to output an error, so use another thread output, or it will block

Note: The above command parameters can be used to check out my other article dedicated to the MySQL backup command parameters, link in this mysql backup command parameters in detail

Java implementation MySQL database automatic backup

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.