文章目录

  • 工具类:
  • service层:
  • 常量:
  • controller:

工具类:

public class MySqlBackupRestoreUtils {/*** 备份数据库* @param host host地址,可以是本机也可以是远程* @param userName 数据库的用户名* @param password 数据库的密码* @param savePath 备份的路径* @param fileName 备份的文件名* @param databaseName 需要备份的数据库的名称* @return* @throws IOException */public static boolean backup(String host, String userName, String password, String backupFolderPath, String fileName,String database) throws Exception {File backupFolderFile = new File(backupFolderPath);if (!backupFolderFile.exists()) {// 如果目录不存在则创建backupFolderFile.mkdirs();}if (!backupFolderPath.endsWith(File.separator) && !backupFolderPath.endsWith("/")) {backupFolderPath = backupFolderPath + File.separator;}// 拼接命令行的命令String backupFilePath = backupFolderPath + fileName;StringBuilder stringBuilder = new StringBuilder();stringBuilder.append("mysqldump --opt ").append(" --add-drop-database ").append(" --add-drop-table ");stringBuilder.append(" -h").append(host).append(" -u").append(userName).append(" -p").append(password);stringBuilder.append(" --result-file=").append(backupFilePath).append(" --default-character-set=utf8 ").append(database);// 调用外部执行 exe 文件的 Java APIProcess process = Runtime.getRuntime().exec(getCommand(stringBuilder.toString()));if (process.waitFor() == 0) {// 0 表示线程正常终止System.out.println("数据已经备份到 " + backupFilePath + " 文件中");return true;}return false;}/*** 还原数据库* @param restoreFilePath 数据库备份的脚本路径* @param host IP地址* @param database 数据库名称* @param userName 用户名* @param password 密码* @return*/public static boolean restore(String restoreFilePath, String host, String userName, String password, String database)throws Exception {File restoreFile = new File(restoreFilePath);if (restoreFile.isDirectory()) {for (File file : restoreFile.listFiles()) {if (file.exists() && file.getPath().endsWith(".sql")) {restoreFilePath = file.getAbsolutePath();break;}}}StringBuilder stringBuilder = new StringBuilder();stringBuilder.append("mysql -h").append(host).append(" -u").append(userName).append(" -p").append(password);stringBuilder.append(" ").append(database).append(" < ").append(restoreFilePath);try {Process process = Runtime.getRuntime().exec(getCommand(stringBuilder.toString()));if (process.waitFor() == 0) {System.out.println("数据已从 " + restoreFilePath + " 导入到数据库中");}} catch (IOException e) {e.printStackTrace();return false;}return true;}private static String[] getCommand(String command) {String os = System.getProperty("os.name");  String shell = "/bin/bash";String c = "-c";if(os.toLowerCase().startsWith("win")){  shell = "cmd";c = "/c";}  String[] cmd = { shell, c, command };return cmd;}public static void main(String[] args) throws Exception {String host = "localhost";String userName = "root";String password = "123456";String database = "mango";System.out.println("开始备份");String backupFolderPath = "c:/dev/";String fileName = "mango.sql";backup(host, userName, password, backupFolderPath, fileName, database);System.out.println("备份成功");System.out.println("开始还原");String restoreFilePath = "c:/dev/mango.sql";restore(restoreFilePath, host, userName, password, database);System.out.println("还原成功");}}

service层:

@Service
public class MysqlBackupServiceImpl implements MysqlBackupService {@Overridepublic boolean backup(String host, String userName, String password, String backupFolderPath, String fileName,String database) throws Exception {return MySqlBackupRestoreUtils.backup(host, userName, password, backupFolderPath, fileName, database);}@Overridepublic boolean restore(String restoreFilePath, String host, String userName, String password, String database)throws Exception {return MySqlBackupRestoreUtils.restore(restoreFilePath, host, userName, password, database);}}
@Component
@ConfigurationProperties(prefix = "mango.backup.datasource")
public class BackupDataSourceProperties {private String host;private String userName;private String password;private String database;public String getHost() {return host;}public void setHost(String host) {this.host = host;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getDatabase() {return database;}public void setDatabase(String database) {this.database = database;}}

常量:

public interface BackupConstants {/** 备份目录名称 */public static final String BACKUP_FOLDER_NAME = "_my_backup";/** 备份目录 */public static final String BACKUP_FOLDER = System.getProperty("user.home") + File.separator + BACKUP_FOLDER_NAME + File.separator;/** 还原目录,默认就是备份目录 */public static final String RESTORE_FOLDER = BACKUP_FOLDER;/** 日期格式 */public static final String DATE_FORMAT = "yyyy-MM-dd_HHmmss";/** SQL拓展名 */public static final String SQL_EXT = ".sql";/** 默认备份文件名 */public static final String BACKUP_FILE_NAME = "my" + SQL_EXT;/** 默认备份还原目录名称 */public static final String DEFAULT_BACKUP_NAME = "backup";/** 默认备份还原文件 */public static final String DEFAULT_RESTORE_FILE = BACKUP_FOLDER + DEFAULT_BACKUP_NAME + File.separator + BACKUP_FILE_NAME;}

controller:

@RestController
@RequestMapping("/backup")
public class MySqlBackupController {@AutowiredMysqlBackupService mysqlBackupService;@AutowiredBackupDataSourceProperties properties;@GetMapping("/backup")public HttpResult backup() {String backupFodlerName = BackupConstants.DEFAULT_BACKUP_NAME + "_" + (new SimpleDateFormat(BackupConstants.DATE_FORMAT)).format(new Date());return backup(backupFodlerName);}private HttpResult backup(String backupFodlerName) {String host = properties.getHost();String userName = properties.getUserName();String password = properties.getPassword();String database = properties.getDatabase();String backupFolderPath = BackupConstants.BACKUP_FOLDER + backupFodlerName + File.separator;String fileName = BackupConstants.BACKUP_FILE_NAME;try {boolean success = mysqlBackupService.backup(host, userName, password, backupFolderPath, fileName, database);if(!success) {HttpResult.error("数据备份失败");}} catch (Exception e) {return HttpResult.error(500, e.getMessage());}return HttpResult.ok();}@GetMapping("/restore")public HttpResult restore(@RequestParam String name) throws IOException {String host = properties.getHost();String userName = properties.getUserName();String password = properties.getPassword();String database = properties.getDatabase();String restoreFilePath = BackupConstants.RESTORE_FOLDER + name;try {mysqlBackupService.restore(restoreFilePath, host, userName, password, database);} catch (Exception e) {return HttpResult.error(500, e.getMessage());}return HttpResult.ok();}@GetMapping("/findRecords")public HttpResult findBackupRecords() {if(!new File(BackupConstants.DEFAULT_RESTORE_FILE).exists()) {// 初始默认备份文件backup(BackupConstants.DEFAULT_BACKUP_NAME);}List<Map<String, String>> backupRecords = new ArrayList<>();File restoreFolderFile = new File(BackupConstants.RESTORE_FOLDER);if(restoreFolderFile.exists()) {for(File file:restoreFolderFile.listFiles()) {Map<String, String> backup = new HashMap<>();backup.put("name", file.getName());backup.put("title", file.getName());if(BackupConstants.DEFAULT_BACKUP_NAME.equalsIgnoreCase(file.getName())) {backup.put("title", "系统默认备份");}backupRecords.add(backup);}}// 排序,默认备份最前,然后按时间戳排序,新备份在前面backupRecords.sort((o1, o2) -> BackupConstants.DEFAULT_BACKUP_NAME.equalsIgnoreCase(o1.get("name")) ? -1: BackupConstants.DEFAULT_BACKUP_NAME.equalsIgnoreCase(o2.get("name")) ? 1 : o2.get("name").compareTo(o1.get("name")));return HttpResult.ok(backupRecords);}@GetMapping("/delete")public HttpResult deleteBackupRecord(@RequestParam String name) {if(BackupConstants.DEFAULT_BACKUP_NAME.equals(name)) {       return HttpResult.error("系统默认备份无法删除!");}String restoreFilePath = BackupConstants.BACKUP_FOLDER + name;try {FileUtils.deleteFile(new File(restoreFilePath));} catch (Exception e) {return HttpResult.error(500, e.getMessage());}return HttpResult.ok();}}

案例代码:sprimngboot备份数据库相关推荐

  1. php下载文件代码 数据库,PHP备份数据库生成SQL文件并下载的函数代码

    . 代码如下: /****** 备份数据库结构 ******/ /* 函数名称:table2sql() 函数功能:把表的结构转换成为SQL 函数参数:$table: 要进行提取的表名 返 回 值:返回 ...

  2. php mysql备份代码_PHP备份/还原MySQL数据库的代码

    以下是代码: 一.备份数据库并下载到本地[db_backup.php] // 设置SQL文件保存文件名 $filename=date("Y-m-d_H-i-s")."-& ...

  3. mySQL数据库中的备份代码_MySQL中的备份数据库

    我目前正在学习SQL.我在windows 10-cmd上运行mysql 8.0.16cli,我以root mysql用户身份登录,并以管理员身份运行cmd. 我想做的是备份我新创建的数据库. 这是我的 ...

  4. 1 shell备份数据库MYSQL案例

    SHELL编程实战MYSQL备份脚本(编程思路) 1.备份MYSQL数据库,备份的工具的选择: 数据量小于100G使用全备,基于mysqldump工具备份,备份会锁表: 数据量大于100G使用增量备份 ...

  5. java s2 宠物商店_北大青鸟accp S2 java宠物商店项目案例代码有数据库表

    [实例简介] 这是 北大青鸟 6.0 S2 JAVA课本的项目案例 代码有注视 [实例截图] [核心代码] 51071f31-b79d-42d6-9b52-feb0304525bc └── ch15 ...

  6. 如何定时备份数据库并上传七牛云

    前言: 这篇文章主要记录自己在备份数据库文件中踩的坑和解决办法. 服务器数据库备份文件之后上传到七牛云 备份数据库文件 在服务器根目录下 创建 /backup/qiniu/.backup.sh #!/ ...

  7. mysql数据库备份总结_mysql中mysqlhotcopy备份数据库总结

    mysqlhotcopy是mysql数据库中一个备份工具,相对于mysqldump是一个快速文件意义上的COPY,mysqlhotcopy是一个数据库端的SQL语句集合. mysqlhotcopy用法 ...

  8. MySQL 实战 定时备份数据库

    在操作数据过程中,可能会导致数据错误,甚至数据库奔溃,而有效的定时备份能很好地保护数据库.本篇文章主要讲述了几种方法进行 MySQL 定时备份数据库. 一. mysqldump命令备份数据 在MySQ ...

  9. 如何实现php自动备份数据库,使用php自动备份数据库表的实现方法

    1.前言 mysql数据库的备份方式有很多: 例如: 1.使用mysqldump函数 mysqldump -u username -p dbname table1 table2 ... > Ba ...

最新文章

  1. 怎么把写好的python代码打包成exe-详解如何将python3.6软件的py文件打包成exe程序...
  2. meta http-equiv=X-UA-Compatible content=IE=7 /意思是将IE8用IE7进行渲染,使网页在IE8下正常...
  3. 腾讯关系型数据库达成“双百”里程碑——6大企业级MySQL特性全面解析
  4. python3小游戏源代码_Python3制作仿“FlappyBird”小游戏|python3教程|python入门|python教程...
  5. 震惊,用了这么多年的 CPU 利用率,其实是错的
  6. Win32 的dll导入问题总结-------------
  7. Linux基础_合并,归档,压缩,dump,编辑器
  8. weex入门指南--华岭
  9. android log4j日志管理的使用
  10. 基于 display 和 javaScript 封装一个页面布局小插件
  11. php openoffice,php实现openoffice转pdf的方法
  12. 软件工程---gjb438b 质量规范体系
  13. NLPIR在线系统介绍
  14. 关于vlan tag untag 标签 区别
  15. 超长正整数的加法(酷勤网)
  16. 转载 Android端调用Caffe模型实现CNN分类
  17. 如何快速格式化重置Mac
  18. 字节跳动布局游戏,打算从腾讯的碗里“抢饭吃”?
  19. python 编写的 pdf 裁剪工具 删除空白页
  20. TypeError: can‘t compare offset-naive and offset-aware datetimes

热门文章

  1. sql长整型_SQL性能优化,太太太太太太太有用了!
  2. jdbc连接数据scanip_java数据库连接_jdbc
  3. 计算机打印机用户,如何:在 Windows 窗体中选择连接到用户计算机的打印机
  4. 【机器学习算法专题(蓄力计划)】二、机器学习中的统计学习方法概论
  5. 七十二、区间合并,插入求交集, 删除被覆盖区间
  6. 二十一、深入Python强大的装饰器
  7. 今日arXiv精选 | 11篇ICCV 2021最新论文
  8. 采样算法哪家强?一个针对主流采样算法的比较
  9. 浅谈 CTR 预估模型发展史
  10. 3.2 使用pytorch搭建AlexNet并训练花分类数据集