java 实现 mysql 数据库导出与导入(适合linux和windows)

备份

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;


public class DataBackup {
	public static void main(String[] args) {
		backup();
	}
	


	public static void backup() {
		try {
		Runtime rt = Runtime.getRuntime();

		Process child = rt.exec("D:/MySQL/MySQL Server 5.6/bin/mysqldump -uroot -p123456 -R -c --set-charset=utf8 senyuan");
		InputStream in = child.getInputStream();
		InputStreamReader xx = new InputStreamReader(in, "utf8");
		String inStr;
		StringBuffer sb = new StringBuffer("");
		String outStr;
		BufferedReader br = new BufferedReader(xx);
		while ((inStr = br.readLine()) != null) {
		sb.append(inStr + "\r\n");
		}
		outStr = sb.toString();

		FileOutputStream fout = new FileOutputStream("E:/sql/qq.sql");
		OutputStreamWriter writer = new OutputStreamWriter(fout, "utf8");
		writer.write(outStr);
		writer.flush();

		in.close();
		xx.close();
		br.close();
		writer.close();
		fout.close();
		} catch (Exception e) {
		e.printStackTrace();
		}

		}

}


导入

public static void load() {
try {
String fPath = "备份的文件路径名";
Runtime rt = Runtime.getRuntime();

Process child = rt.exec("mysql -u用户名 -p密码 数据库名");
OutputStream out = child.getOutputStream();
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);
writer.flush();

out.close();
br.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}



你可能感兴趣的:(java 实现 mysql 数据库导出与导入(适合linux和windows))