Java implementation MySQL database backup

Source: Internet
Author: User
Tags readline win32 stringbuffer

Package com.itenp.gen.action;

Import Java.io.BufferedReader;

Import Java.io.FileInputStream;

Import Java.io.FileOutputStream;

Import Java.io.InputStream;

Import Java.io.InputStreamReader;

Import Java.io.OutputStreamWriter;

Import Java.text.SimpleDateFormat;

Import Java.util.Date;

Import Java.util.HashMap;

Import java.util.List;

Import Java.util.Map;

Import Javax.annotation.Resource;

Import Org.apache.log4j.Logger;

Import Org.springframework.context.annotation.Scope;

Import Org.springframework.stereotype.Controller;

Import com.itenp.gen.common.Constants;

Import Com.itenp.gen.common.ParameterUtil;

Import com.itenp.gen.service.i.backupservicei;

Import Com.itenp.gen.system.PropertiesCache;

Import Com.itenp.gen.vo.BackUpVO;

Import Com.itenp.gen.vo.UserVO;

@SuppressWarnings ("Serial")

@Scope ("prototype")

@Controller ("Backupaction")

public class Backupaction extends Baseaction {

private static Logger log = Logger.getlogger (Backupaction.class);

Private String databasedirectory = Propertiescache.getinstance (). Getdatabasedirectory (); Database bin Path

Private String DatabaseName = Propertiescache.getinstance (). GetDatabaseName ();//Database name

Private String UserName = Propertiescache.getinstance (). GetUserName ();

Private String userpwd = Propertiescache.getinstance (). GETUSERPWD ();

Private String Copydbcmd = Propertiescache.getinstance (). Getcopydbcmd ();//Database Backup command

Private String Copyproccmd = Propertiescache.getinstance (). Getcopyproccmd ();//Storage Engineering Backup command

Private String Copyedfilepath = Propertiescache.getinstance (). Getcopyedfilepath (); Where to store files after backup

Private String Restorecmd = Propertiescache.getinstance (). Getrestorecmd (); Database Restore command

Private String msg = "";

Private String MSG1 = "";

Private BACKUPSERVICEI service;

@Resource (name= "Backupservice")

public void Setbackupservice (BACKUPSERVICEI service) {

This.service=service;

}

@SuppressWarnings ("Unchecked")

Public String list () throws Exception

{

System.out.println ("Copyedfilepath" +copyedfilepath);

HashMap map = new HashMap ();

Get a list of eligible records

list<backupvo> list = (list) service.findlist (map);

Request.setattribute ("list", list);

Log.debug ("# # #" +propertiescache.getinstance (). Gettemplatedirectory ());

System.out.println (Propertiescache.getinstance (). Gettemplatedirectory ());

Return "Success";

}

@SuppressWarnings ("Unchecked")

Public String Backup () throws Exception

{

Runtime RT = Runtime.getruntime ();

Call the MySQL cmd:

/*SYSTEM.OUT.PRINTLN ("Database bin path" +databasedirectory);

SYSTEM.OUT.PRINTLN ("database name" +databasename);

System.out.println ("User name" +username);

SYSTEM.OUT.PRINTLN ("password" +userpwd);

SYSTEM.OUT.PRINTLN ("Database backup command" +copydbcmd);

SYSTEM.OUT.PRINTLN ("Storage Engineering backup Command" +COPYPROCCMD); */

String str = databasedirectory+ "/" +copydbcmd+ "--no-defaults" + "-U" +username+ "" + "-P" +userpwd+ "" +copyproccmd+ "" + "-- Set-charset=utf-8 "+" "+databasename;

str = "D:\SOFT\MySQL\MySQL Server 5.5\bin/mysqldump-uroot-proot-r--set-charset=utf-8 nlnk";

System.out.println (str);

Process child = rt.exec (databasedirectory+ "/" +copydbcmd+ "" + "-U" +username+ "" + "-P" +userpwd+ "" +copyproccmd+ "" + "-- Set-charset=utf-8 "+" "+databasename");//Set export encoding to UTF8. This must be UTF8.

Process child = rt.exec (str);//Set export encoding to UTF8. This must be UTF8.

Call MySQL cmd: Back up a table

Process childtable = RT

. EXEC ("D:/db/mysql/mysql-5.0.45-win32/bin/mysqldump-uroot-pmysql--set-charset=utf8 ibtts T_a_dbbak");// Set the export encoding to UTF8. This must be UTF8.

Process childtable = RT

. EXEC (databasedirectory+ "/" +copydbcmd+ "" + "-U" +username+ "" + "-P" +userpwd+ "" + "--set-charset=utf8" + "" + databasename+ "" + "T_a_dbbak");//Set export encoding to UTF8. This must be UTF8.

Writes the console output information from the process execution to the. sql file, which generates the backup file. Note: If you do not read the console information, it will cause the process to become blocked from running

InputStream in = Child.getinputstream ();//console output information as input stream

InputStreamReader xx = new InputStreamReader (in, "UTF8");//Set output stream encoding to UTF8. This must be UTF8, otherwise the read from the stream is garbled

String inStr;

StringBuffer sb = new StringBuffer ("");

String outstr;

Combining console output information strings

BufferedReader br = new BufferedReader (XX);

System.out.println ("------------" +br.readline ());

while ((inStr = Br.readline ()) = null) {

Sb.append (inStr + "\ r \ n");

}

outstr = Sb.tostring ();

Determine if the save is successful

if (outstr! = null &&!outstr.trim (). Equals ("")) {

Msg= "OK";

}

SYSTEM.OUT.PRINTLN ("-----" +outstr);

Create file name

SimpleDateFormat format = new SimpleDateFormat ("Yyyymmddhhmmss");

String Today=format.format (New Date ());

String targetdirectory = Scontext.getrealpath ("/web-inf/dbbackup");

System.out.println (targetdirectory);

SQL target file to use for import: D:/ibtts.sql

FileOutputStream fout = new FileOutputStream (

copyedfilepath+ "/" +today+ "Ibtts.sql");

OutputStreamWriter writer = new OutputStreamWriter (fout, "UTF8");

Writer.write (OUTSTR);

Note: If the file is written in buffer mode, it will result in Chinese garbled, and the flush () method can avoid

Writer.flush ();

Don't forget to close the input and output stream

In.close ();

Xx.close ();

Br.close ();

Writer.close ();

Fout.close ();

SYSTEM.OUT.PRINTLN ("/* Output ok! */");

Adding data to the database

HashMap map = new HashMap ();

Map.put ("db_nm", "Ibtts");

Map.put ("bk_nm", today+ "Ibtts.sql");

Map.put ("Bk_user", ((Uservo) Session.get (Constants.s_login_user)). getuser_id ());

Service.create (map);

Copytable ();

return list ();

}

/**

* Recovery of data

*/

@SuppressWarnings ("Unchecked")

Public String Load () throws Exception

{

Copytable ();

Get all the parameters of the page

map<string, string> map = Parameterutil.getstringmap (request,session);

String targetdirectory = Scontext.getrealpath ("/web-inf/dbbackup");

Query after getting the ID

BACKUPVO vo= (BACKUPVO) Service.findbyid (map);

String fpath=copyedfilepath+ "/" +vo.getbk_nm ();

System.out.println (Fpath);

Map.put ("Id", Vo.getid ());

String Fpath = "D:/ibtts.sql"; Runtime RT = Runtime.getruntime ();

Call the MySQL cmd:

Process child = Rt.exec ("D:/db/mysql/mysql-5.0.45-win32/bin/mysql-uroot-pmysql Ibtts");

Process child = rt.exec (databasedirectory+ "/" +restorecmd+ "" + "-U" +username+ "" + "-P" +userpwd+ "" +databasename ");

System.out.println (databasedirectory+ "/" +restorecmd+ "" + "-U" +username+ "" + "-P" +userpwd+ "" +databasename ");

Java.io.OutputStream out =child.getoutputstream ();//console input information as the output stream

String inStr;

StringBuffer sb = new StringBuffer ("");

String outstr;

BufferedReader br = new BufferedReader (New InputStreamReader (

New FileInputStream (Fpath), "UTF8");

while ((inStr = Br.readline ()) = null) {

Sb.append (inStr + "\ r \ n");

}

outstr = Sb.tostring ();

OutputStreamWriter writer = new OutputStreamWriter (out, "UTF8");

Writer.write (OUTSTR);

Note: If the file is written in buffer mode, it will result in Chinese garbled, and the flush () method can avoid

Writer.flush ();

Don't forget to close the input and output stream

Out.close ();

Br.close ();

Writer.close ();

Get restore User

Map.put ("Restore_user", ((Uservo) Session.get (Constants.s_login_user)). getuser_id ());

Service.modify (map);

Restoretable (map); //---------------

SYSTEM.OUT.PRINTLN (map);

SYSTEM.OUT.PRINTLN ("recovery success");

Request.getsession (). SetAttribute ("Dbmap", map);

MSG1 = "Tiaozhuan";

Return "Success";

}

Handling of specific tables

public void Copytable () throws Exception

{

Runtime RT = Runtime.getruntime ();

Call the MySQL cmd:

Call MySQL cmd: Back up a table

Process child = RT

. EXEC ("D:/db/mysql/mysql-5.0.45-win32/bin/mysqldump-uroot-pmysql--set-charset=utf8 ibtts T_a_dbbak");// Set the export encoding to UTF8. This must be UTF8.

Process child = rt.exec (databasedirectory+ "/" +copydbcmd+ "--no-defaults" + "-U" +username+ "" + "-P" +userpwd+ "" + "-- Set-charset=utf8 "+" "+databasename+" "+" T_a_dbbak ");//Set export encoding to UTF8. This must be UTF8.

Writes the console output information from the process execution to the. sql file, which generates the backup file. Note: If you do not read the console information, it will cause the process to become blocked from running

InputStream in = Child.getinputstream ();//console output information as input stream

System.out.println (databasedirectory+ "/" +copydbcmd+ "--no-defaults" + "-U" +username+ "" + "-P" +userpwd+ "" + "-- Set-charset=utf8 "+" "+databasename+" "+" T_a_dbbak ");

InputStreamReader xx = new InputStreamReader (in, "UTF8");//Set output stream encoding to UTF8. This must be UTF8, otherwise the read from the stream is garbled

String inStr;

StringBuffer sb = new StringBuffer ("");

String outstr;

Combining console output information strings

BufferedReader br = new BufferedReader (XX);

while ((inStr = Br.readline ()) = null) {

Sb.append (inStr + "\ r \ n");

}

outstr = Sb.tostring ();

String targetdirectory = Scontext.getrealpath ("/web-inf/dbbackup");

SQL target file to use for import: D:/ibtts.sql

FileOutputStream fout = new FileOutputStream (

copyedfilepath+ "/" + "Ibtts_talbe.sql");

OutputStreamWriter writer = new OutputStreamWriter (fout, "UTF8");

Writer.write (OUTSTR);

Note: If the file is written in buffer mode, it will result in Chinese garbled, and the flush () method can avoid

Writer.flush ();

Don't forget to close the input and output stream

In.close ();

Xx.close ();

Br.close ();

Writer.close ();

Fout.close ();

}

public void restoretable (map map) throws Exception

{

String fpath=copyedfilepath+ "/" + "ibtts_talbe.sql";

String Fpath = "D:/ibtts.sql"; Runtime RT = Runtime.getruntime ();

Call the MySQL cmd:

Process child = Rt.exec ("D:/db/mysql/mysql-5.0.45-win32/bin/mysql-uroot-pmysql Ibtts");

Process child = rt.exec (databasedirectory+ "/" +restorecmd+ "" + "-U" +username+ "" + "-P" +userpwd+ "" +databasename ");

System.out.println (databasedirectory+ "/" +restorecmd+ "" + "-U" +username+ "" + "-P" +userpwd+ "" +databasename ");

Java.io.OutputStream out =child.getoutputstream ();//console input information as the output stream

String inStr;

StringBuffer sb = new StringBuffer ("");

String outstr;

BufferedReader br = new BufferedReader (New InputStreamReader (

New FileInputStream (Fpath), "UTF8");

while ((inStr = Br.readline ()) = null) {

Sb.append (inStr + "\ r \ n");

}

outstr = Sb.tostring ();

OutputStreamWriter writer = new OutputStreamWriter (out, "UTF8");

Writer.write (OUTSTR);

Note: If the file is written in buffer mode, it will result in Chinese garbled, and the flush () method can avoid

Writer.flush ();

Don't forget to close the input and output stream

Out.close ();

Br.close ();

Writer.close ();

SYSTEM.OUT.PRINTLN (map);

/*int sign=0;

BACKUPVO Vo=null;

while (Vo==null) {

vo= (BACKUPVO) Service.findbyid (map);

if (vo!=null| | SIGN==100) {

Break

}

sign++;

}

Service.modify (map); */

}

@SuppressWarnings ("Unchecked")

Public String Upbak () throws exception{

HashMap map = new HashMap ();

Map = (HASHMAP) request.getsession (). getattribute ("Dbmap");

int sign=0;

BACKUPVO Vo=null;

while (Vo==null) {

vo= (BACKUPVO) Service.findbyid (map);

if (vo!=null| | SIGN==100) {

Break

}

sign++;

}

Service.modify (map);

return list ();

}

Public String getmsg () {

return msg;

}

public void Setmsg (String msg) {

this.msg = msg;

}

Public String GETMSG1 () {

return MSG1;

}

public void SetMsg1 (String msg1) {

THIS.MSG1 = MSG1;

}

}

Get ""

    • This article is from: Linux Tutorial Network

Java implementation MySQL database backup

Related Article

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.