以SQL文件的形式导出MySQL数据库并还原
package com.source.script;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Date;
/**
* @author 016540
*
*/
public class Export {
public static void export(){
String path="C:/back5.sql";
String dumpCommand = "mysqldump -uroot -proot phonemailsystem -r " + path;
File tst = new File(path);
FileWriter fw = null;
try{
fw = new FileWriter(tst);
fw.close();
}catch(IOException ex){
ex.printStackTrace();
}
Runtime rt = Runtime.getRuntime();
try {
Process proc = rt.exec(dumpCommand);
InputStream in = proc.getInputStream();
InputStreamReader read = new InputStreamReader(in,"utf8");
BufferedReader br = new BufferedReader(read);
BufferedWriter bw = new BufferedWriter(new FileWriter(tst,true));
String line=null;
StringBuffer buffer = new StringBuffer();
while((line=br.readLine())!=null){
buffer.append(line+"\n");
}
String toWrite = buffer.toString();
bw.write(toWrite);
bw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void load(String str) {
String filepath = "C:\\back4.sql"; // 备份的路径地址
//新建数据库test
// String stmt1 = "mysqladmin -u root -proot create phonemailsystem";
String stmt2 = "mysql -u root -proot phonemailsystem < " + filepath;
String[] cmd = { "cmd", "/c", stmt2 };
try {
// Runtime.getRuntime().exec(stmt1);
Runtime.getRuntime().exec(cmd);
System.out.println("数据已从 " + filepath + " 导入到数据库中");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]){
System.out.println(new Date());
System.out.println("正在导出。。。。。");
export();
System.out.println(new Date());
//load("");
}
}