前言
为了应对项目中数据库突然奔溃,导致丢失数据,这时可以通过代码实现数据库的定时备份与恢复,即使数据库宕机了,我们也可以将之前备份好的数据信息还原到数据库。通过java代码实现数据库的备份与恢复,其实就是通过java代码操作命令行。那么如何实现数据库的备份与恢复呢,下面案例可供参考。
一、数据库备份
/**
* 数据库文件备份
*/
@RequestMapping("/doBackup")
public R doBackup(){
System.out.println("现在时间是"+new Date());
Runtime runtime = Runtime.getRuntime(); //获取Runtime实例
String database1 = "equipments"; // 需要备份的数据库名
Date currentDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
String sdfDate = sdf.format(currentDate);
String filepath = "d:\\sql\\time_" + sdfDate + ".sql"; // 备份的路径地址
//执行命令(此处需要定位到mysqldump.exe路径,--default-character-set=gbk是为了解决中文乱码问题)
String stmt = "d:\\wamp64\\bin\\mysql\\mysql5.7.24\\bin\\mysqldump -h localhost -uroot -p12345678 --default-character-set=gbk "+database1+" > "+filepath;
System.out.println(stmt);
try {
String[] command = { "cmd", "/c", stmt};
Process process = runtime.exec(command);
InputStream input = process.getInputStream();
System.out.println(IOUtils.toString(input, "UTF-8"));
//若有错误信息则输出
InputStream errorStream = process.getErrorStream();
System.out.println(IOUtils.toString(errorStream, "gbk"));
//保存备份数据信息到数据库中
SqlFileEntity sqlFileEntity = new SqlFileEntity();
sqlFileEntity.setName("time_" + sdfDate + ".sql");
sqlFileEntity.setPath(filepath);
sqlFileEntity.setCreateTime(currentDate);
this.save(sqlFileEntity);
} catch (IOException e) {
e.printStackTrace();
}
return R.ok();
}
二、数据库恢复
/**
* 还原数据库
*/
@RequestMapping("/restore")
public R restore(@RequestBody String filename) {
String database = "equipments"; // 需要备份的数据库名
System.out.println("现在时间是" + new Date());
Runtime runtime = Runtime.getRuntime();
try {
String filePath = "d:\\sql\\"+filename; // sql文件路径
String stmt = "mysql -h localhost -uroot -p12345678 "+database+"< " + filePath;
System.out.println(stmt);
String[] command = {"cmd", "/c", stmt};
Process process = runtime.exec(command);
//若有错误信息则输出
InputStream errorStream = process.getErrorStream();
System.out.println(IOUtils.toString(errorStream, "gbk"));
//等待操作
int processComplete = process.waitFor();
if (processComplete == 0) {
System.out.println("还原成功.");
} else {
throw new RuntimeException("还原数据库失败.");
}
} catch (Exception e) {
e.printStackTrace();
}
return R.ok();
}
总结
以上就是今天要讲的内容,本文仅仅简单介绍了java代码实现数据库的备份与恢复,如果要实现数据库的定时备份与恢复,还需要编写定时器或者定时任务,将数据库的备份与恢复添加到定时任务中即可。