首頁 > 資料庫 > mysql教程 > java写的MySQL数据库备份和恢复代码:

java写的MySQL数据库备份和恢复代码:

WBOY
發布: 2016-06-07 15:40:07
原創
1073 人瀏覽過

1.MySQL数据库备份和恢复,java代码实现:详情见下面: package com.spring.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import

1.MySQL数据库备份和恢复,java代码实现:详情见下面:

package com.spring.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

//MYSQL数据库备份
public class MySQLDump {

//备份数据库
public static boolean sqlDump(String cmd,String filePath){
boolean falg = false;
try {
Runtime run = Runtime.getRuntime();
Process p = run.exec(cmd);
InputStream is = p.getInputStream();// 控制台的输出信息作为输入流
InputStreamReader isr = new InputStreamReader(is,"UTF-8");//设置输入流编码格式  
BufferedReader br = new BufferedReader(isr);
//将控制台输入信息写入到文件输出流中 
FileOutputStream fos = new FileOutputStream(filePath);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"));

String temp = null;
while((temp = br.readLine()) != null){
bw.write(temp);
bw.newLine();
}
bw.flush();
bw.close();
br.close();
falg = true;
System.out.println("/* Dump SQL File "+filePath+" OK! */");
} catch (IOException e) {
throw new RuntimeException("请将mysql命令添加到path中!",e);
}
return falg;
}

//恢复数据库
public static void sqlLoad(String cmd,String sqlPath){
try {
Runtime rt = Runtime.getRuntime();
Process child = rt.exec(cmd);
OutputStream out = child.getOutputStream();//控制台的输入信息作为输出流 
//输入流
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(sqlPath),"utf-8"));
//输出流
OutputStreamWriter writer = new OutputStreamWriter(out,"utf-8");
String inStr;
while((inStr = br.readLine()) != null){
writer.write(inStr);
writer.write("\n\r");
}
writer.flush();
//别忘记关闭输出流
out.close();
br.close();
writer.close();
System.out.println("/* Load SQL File "+sqlPath+" OK!*/");
} catch (IOException e) {
throw new RuntimeException(e);
}
}

public static void main(String[] args){
//备份数据库
sqlDump("C:/Program Files/MySQL/MySQL Server 5.5/bin/mysqldump -uroot -proot itcastoa", "d:/itcastOA.sql");
//恢复数据库
sqlLoad("C:/Program Files/MySQL/MySQL Server 5.5/bin/mysql.exe -uroot -proot itcastoa", "d:/itcastOA.sql");
}

}

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板