在开发系统过程中,经常存在数据库备份还原操作这样的需求,为的是防止数据丢失等问题,这里挨踢书写了一套备份、还原、删除的工具类,欢迎参考。
代码和实际应用存在细微改动,不影响参照
/**
* @author 挨踢小子
* @date 2019-10-17 15:47
*/
public class DBUtils {
/**
* 数据库安装地址
*/
public static final String host = "127.0.0.1";
/**
* 操作数据库
*/
public static final String dbName = "***";
/**
* 用户名
*/
public static final String root = "***";
/**
* 密码
*/
public static final String pwd = "***";
/**
* 备份位置
*/
public static final String backPath = "E:/workPro/work/sql/";
/**
* 备份文件命名规则
*/
public static final String fileName = "work.sql";
/**
* MySQL命令工具 绝对路径
*/
public static final String toolPath = "D:/phpstudy/PHPTutorial/MySQL/bin/";
}
/**
*
* @author Aiti
* @date 2019-10-17
*/
public class DbmanageImpl extends DBUtils {
/**
* 备份操作工具
*/
public boolean dbBackUp() {
//最终文件名
String finalFileName = System.currentTimeMillis() + fileName;
String pathSql = backPath + finalFileName;
File fileSql = new File(pathSql);
//创建备份sql文件
if (!fileSql.exists()) {
try {
fileSql.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
StringBuffer sb = new StringBuffer();
sb.append(toolPath + "mysqldump");
sb.append(" -h" + host);
sb.append(" -u" + root);
sb.append(" -p" + pwd);
sb.append(" " + dbName + " >");
sb.append(pathSql);
System.out.println("cmd命令为:" + sb.toString());
System.out.println("开始备份:" + dbName);
Runtime runtime = Runtime.getRuntime();
try {
Process process = runtime.exec("cmd /c " + sb.toString());
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 数据恢复操作工具
*/
public boolean dbRestore(String fileName) {
String filePath = backPath + fileName;
StringBuilder sb = new StringBuilder();
sb.append(toolPath + "mysql");
sb.append(" -h" + host);
sb.append(" -u" + root);
sb.append(" -p" + pwd);
sb.append(" " + dbName + " <");
sb.append(filePath);
System.out.println("cmd命令为:" + sb.toString());
Runtime runtime = Runtime.getRuntime();
System.out.println("开始还原数据");
try {
//插入数据库备份恢复记录表
Process process = runtime.exec("cmd /c" + sb.toString());
InputStream is = process.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(is, "utf8"));
String line = null;
while ((line = bf.readLine()) != null) {
System.out.println(line);
}
is.close();
bf.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 删除数据备份
*/
public String remove(String fileName)
{
String file= DBUtils.backPath + fileName;
File del_file = new File(file);
if(del_file.isFile()){
if(del_file.delete()==false){
return "删除失败";
}
}
return "删除成功"
}
1、为啥我在电脑上定义了环境变量,为何不能直接使用 mysqldump 工具。
Process process = runtime.exec("cmd /c " + sb.toString());
Aiti答:runtime.exec();无法加载本地环境变量,因此需要定义绝对路径处理。
/**
* MySQL命令工具 绝对路径
*/
public static final String toolPath = "D:/phpstudy/PHPTutorial/MySQL/bin/";
以下这些,都是bin目录下,数据库操作相关的可执行文件。