数据库以.sql的备份

/**.
* 将数据库数据备份到文件中
*/
public void backUp(){
String back = "";
String name = getRequest().getParameter("name");
Date date = new Date();
SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
String time = name+"_"+sf.format(date).toString();
try {
Runtime rt = Runtime.getRuntime();
String user = "root"; // 数据库帐号
String password = "root"; // 登陆密码
String database = "produce"; // 需要备份的数据库名
String filepath = "d:\\MySQLBase\\"+time+".sql"; // 备份的路径地址
String stmt1 = "mysqldump " + database + " -R -h 192.168.0.133 " + " -u "
+ user + " -p" + password
+ " --default-character-set=utf8 --triggers -R --hex-blob -x --result-file=" + filepath;
System.out.println("-------:"+stmt1);
// 调用 mysql 的 cmd:
Process child = rt.exec(stmt1);// 设置导出编码为utf8。这里必须是utf8

System.out.println("亲,备份成功了哦!");
back = "1";
} catch (Exception e) {
back = "2";
e.printStackTrace();
}
CommonMethod commonMethod = new CommonMethod();
commonMethod.responseAjax(back, null);
}
/**.
* 将备份文件中的数据还原到数据库
*/
public void recove(){
String back = "";
String file = getRequest().getParameter("file");
file = file.substring(file.lastIndexOf("\\")+1,file.length());
try {
String fPath = "e:/bin/bf.sql";
Runtime rt = Runtime.getRuntime();
String user = "root"; // 数据库帐号
String password = "root"; // 登陆密码
String database = "produce"; // 需要备份的数据库名
String sour = "localhost";
// String filepath = "d:\\MySQLBase\\bf.sql"; // 备份的路径地址
String filepath = "d:\\MySQLBase\\"+file; // 备份的路径地址
// 调用 mysql 的 cmd:
// Process child = rt.exec("mysql -u "+user+" -p "+password+" "+database );
String st = "mysql -h "+sour+" -u "+user+" -p"+password+" -f "+database;
Process child =
rt.exec(st);
System.out.println(st);
OutputStream out = child.getOutputStream();//控制台的输入信息作为输出流
String inStr;
StringBuffer sb = new StringBuffer("");
String outStr;
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(filepath), "utf8"));
while ((inStr = br.readLine()) != null) {
sb.append(inStr + "\r\n");
}
outStr = sb.toString();

OutputStreamWriter writer = new OutputStreamWriter(out, "utf8");
writer.write(outStr);
// 注:这里如果用缓冲方式写入文件的话,会导致中文乱码,用flush()方法则可以避免
writer.flush();
// 别忘记关闭输入输出流
out.close();
br.close();
writer.close();
System.out.println("数据已经恢复了!");
back = "1";
} catch (Exception e) {
back = "2";
e.printStackTrace();
}
CommonMethod commonMethod = new CommonMethod();
commonMethod.responseAjax(back, null);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值