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目錄下創(chuàng)建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 {
// 用于打印執(zhí)行日志
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();
// 創(chuàng)建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;
}
}創(chuàng)建定時任務
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點觸發(fā)一次
@Scheduled(cron = "*/5 * * * * ?") // 5秒觸發(fā)一次
public void task() {
exportSQL.export();
}
}
編寫完成 運行測試一下

我這里項目在D盤中,因此D盤下D:\data\sql 默認會有生成的文件


成功,我這邊測試了一下,數據庫是可以導入的
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
jpa?onetomany?使用級連表刪除被維護表數據時的坑
這篇文章主要介紹了jpa?onetomany?使用級連表刪除被維護表數據時的坑,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
springMVC在restful風格的性能優(yōu)化方案
這篇文章主要介紹了springMVC在restful風格的性能優(yōu)化方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
@Valid 校驗無效,BindingResult未獲得錯誤的解決
這篇文章主要介紹了@Valid 校驗無效,BindingResult未獲得錯誤的解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10

