简单的数据库备份与恢复类
* 数据库备份与恢复类
* @author Administrator
*/
public class Beifen {
/**
* 数据库备份
* @param cmd 备份命令
* @param filePath 备份文件保存位置
* @return
* @throws IOException
*/
public static boolean sqlDump(String cmd, String filePath)
throws IOException {
boolean falg = false;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
FileOutputStream fos = null;
BufferedWriter bw = null;
try {
Runtime run = Runtime.getRuntime();
// cmd 命令:
Process p = run.exec(cmd);
is = p.getInputStream();// 控制台的输出信息作为输入流
isr = new InputStreamReader(is, "UTF-8");// 设置输入流编码格式
br = new BufferedReader(isr);
// 将控制台输入信息写入到文件输出流中
fos = new FileOutputStream(filePath);
bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
String temp = null;
while ((temp = br.readLine()) != null) {
bw.write(temp);
bw.newLine();
}
falg = true;
System.out.println("/* Dump SQL File " + filePath + " OK! */");
} catch (IOException e) {
throw new RuntimeException("请将mysql命令添加到path中!", e);
} finally {
bw.flush();
bw.close();
br.close();
}
return falg;
}
/**
* 恢复数据库
* @param cmd 恢复命令
* @param sqlPath 恢复文件
* @throws IOException
*/
public static void sqlLoad(String cmd, String sqlPath) throws IOException {
OutputStreamWriter writer = null;
OutputStream out = null;
BufferedReader br = null;
try {
Runtime rt = Runtime.getRuntime();
Process child = rt.exec(cmd);
out = child.getOutputStream();// 控制台的输入信息作为输出流
// 输入流
br = new BufferedReader(new InputStreamReader(new FileInputStream(
sqlPath), "utf8"));
// 输出流
writer = new OutputStreamWriter(out, "utf8");
String inStr;
while ((inStr = br.readLine()) != null) {
writer.write(inStr);
writer.write("\r\n");
}
writer.flush();
System.out.println("/* Load SQL File " + sqlPath + " OK! */");
} catch (Exception e) {
e.printStackTrace();
} finally {
//输入输出流
out.close();
br.close();
writer.close();
}
}
/**
* 测试的main方法
* @param args
*/
public static void main(String[] args) {
//备份数据库
boolean b=false;
try {
b =
sqlDump("E:/mysql-5.6.14-winx64/bin/mysqldump -uroot -proot 51sql","c:y_copy04.sql");
} catch (IOException e){
e.printStackTrace();
}
System.out.println("---------------->"+b);
//恢复数据库
// try {
// sqlLoad("E:/mysql-5.6.14-winx64/bin/mysql.exe -uroot -proot 51sql"
// ,"c:y_copy04.sql");
// } catch (IOException e) {
// e.printStackTrace();
// }
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。