springboot项目实现定时备份数据库导出sql文件方式
作者:想太多会累i
这篇文章主要介绍了springboot项目实现定时备份数据库导出sql文件方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
之所以做这个功能的原因是我的服务器上的数据库被攻击了,还好服务器上没有什么重要的数据,但是数据没了就很肉疼,因此做了这个功能,用来定时备份数据库数据
添加依赖
这里用到了 hutool 工具包 这个包挺好用的,推荐大家可以多看看他的官方文档
官方文档:https://www.hutool.cn/docs/#/
<!-- hutool工具类--> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.3.3</version> </dependency>
添加配置文件和配置
因为这里只是需要导出sql 所以就使用了hutool工具中的DB
在resources
目录下创建db.setting
数据库配置文件
文件中内容:
## url 数据库连接地址 ## user 连接数据库账号 ## pass 连接数据库密码 url = jdbc:mysql://localhost:3306/test user = root pass = 123456
紧接着在application.yml
文件中添加sql文件的存放的路径
# 导出sql文件的位置 sql: dbname: notepad # 数据库名 filePath: /data/sql/ # 导出sql文件的位置 win下会直接在项目所在磁盘下建立 data/sql文件
编写导出SQL的方法
方法直接贴在下面:
package com.an.notepad.task; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.date.DateTime; import cn.hutool.core.io.file.FileWriter; import cn.hutool.core.text.StrBuilder; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.db.Db; import cn.hutool.db.Entity; import cn.hutool.db.ds.DSFactory; import lombok.Data; import lombok.SneakyThrows; import lombok.experimental.Accessors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; import java.io.File; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.util.List; @Configuration public class ExportSQL { // 用于打印执行日志 private static final Logger logger = LoggerFactory.getLogger(ExportSQL.class); // 存储的路径 @Value("${sql.filePath}") private String filePath; // 数据库名 @Value("${sql.dbname}") private String database_name; // 需要导出的表名 private final List<TempBean> tempBeanList = CollectionUtil.newArrayList( // 这里写需要存储的表名 有几张表就new几个 new TempBean().setTable("n_note"), new TempBean().setTable("n_user") ); @SneakyThrows public void export() { //获取默认数据源 DataSource ds = DSFactory.get(); // 获取数据库连接对象 Connection connection = ds.getConnection(); // 获取连接信息 DatabaseMetaData metaData = connection.getMetaData(); // 创建sql文件对象 FileWriter sqlFileWriter = FileWriter.create(new File(filePath + database_name + ".sql")); sqlFileWriter.write(""); sqlFileWriter.append("USE " + database_name + ";\n"); sqlFileWriter.append("/*\n"); sqlFileWriter.append(" --------------------------------------------------\n"); sqlFileWriter.append(" Target Server Type : " + metaData.getDatabaseProductName() + ";\n"); sqlFileWriter.append(" Target Server Version : " + metaData.getDatabaseProductVersion() + ";\n"); sqlFileWriter.append(" \n"); sqlFileWriter.append(" Target Server Date : " + DateTime.now() + ";\n"); sqlFileWriter.append(" \n"); sqlFileWriter.append(" --------------------------------------------------\n"); sqlFileWriter.append("*/\n"); sqlFileWriter.append("SET NAMES utf8mb4;\n"); sqlFileWriter.append("SET FOREIGN_KEY_CHECKS = 0;\n"); for (TempBean tempBean : tempBeanList) { String table = tempBean.table; sqlFileWriter.append("\n\n\n"); // DROP TABLE sqlFileWriter.append("DROP TABLE IF EXISTS `" + table + "`;\n"); // CREATE TABLE Entity createTableEntity = Db.use().queryOne("SHOW CREATE TABLE " + table); sqlFileWriter.append((String) createTableEntity.get("Create Table")); sqlFileWriter.append(";\n"); // 看配置,是否需要insert语句 if (!tempBean.insert) { continue; } // INSERT INTO List<Entity> dataEntityList = Db.use().query("SELECT * FROM " + table); for (Entity dataEntity : dataEntityList) { StrBuilder field = StrBuilder.create(); StrBuilder data = StrBuilder.create(); dataEntity.forEach((key, value) -> { field.append(key).append(", "); if (ObjectUtil.isNotNull(value)) { if (StrUtil.equals("true", String.valueOf(value))) { data.append("b'1'"); } else if (StrUtil.equals("false", String.valueOf(value))) { data.append("b'0'"); } else { data.append("'").append(value).append("'"); } } else { data.append("NULL"); } data.append(", "); }); sqlFileWriter.append("INSERT INTO `" + table + "`("); String fieldStr = field.subString(0, field.length() - 2); sqlFileWriter.append(fieldStr); sqlFileWriter.append(") VALUES ("); String dataStr = data.subString(0, data.length() - 2); sqlFileWriter.append(dataStr); sqlFileWriter.append(");\n"); } } sqlFileWriter.append("\n\n\n"); sqlFileWriter.append("SET FOREIGN_KEY_CHECKS = 1;\n"); logger.info(">>>>>>>>>> 存储sql成功" + DateTime.now()); } @Data @Accessors(chain = true) static class TempBean { // 表名 public String table; // 是否需要insert语句,默认需要 (表中数据) public Boolean insert = true; } }
创建定时任务
package com.an.notepad.task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; /** * 定时导出数据库sql功能 */ @Configuration @EnableScheduling // 开启定时任务 public class ExportTask { @Autowired private ExportSQL exportSQL; //@Scheduled(cron = "0 0 1 * * ?") // 每天凌晨1点触发一次 @Scheduled(cron = "*/5 * * * * ?") // 5秒触发一次 public void task() { exportSQL.export(); } }
编写完成 运行测试一下
我这里项目在D盘
中,因此D盘
下D:\data\sql
默认会有生成的文件
成功,我这边测试了一下,数据库是可以导入的
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。