springboot 容器加载完成后执行sql脚本


import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author lidg
 * @date 2022/6/28
 * @desc
 */
@Component
@Order(value = 1)
public class SysMgrSlqScriptRunner implements ApplicationRunner {

	private static final Logger logger = LoggerFactory.getLogger(SysMgrSlqScriptRunner.class);

	@Autowired
	private DataSource dataSource;

	@Override
	public void run(ApplicationArguments args) throws Exception {
		String scriptPath = "db/ca.sql";
		execSqlScript(dataSource, scriptPath);
		}

	}

	/**
	 * 脚本执行
	 *
	 * @param dataSource  数据源
	 * @param sqlFilePath 脚本路径
	 *
	 * @throws IOException
	 */
	public static void execSqlScript(DataSource dataSource, String sqlFilePath) throws IOException {
		// 通过数据源获取数据库连接
		Connection connection = DataSourceUtils.getConnection(dataSource);
		// 创建脚本执行器
		ScriptRunner scriptRunner = new ScriptRunner(connection);
		// 设置执行器日志输出
		StringWriter writer = new StringWriter();
		PrintWriter printWriter = new PrintWriter(writer);
		scriptRunner.setLogWriter(printWriter);
		// 设置执行器错误日志输出
		StringWriter errorWriter = new StringWriter();
		PrintWriter errorPrintWriter = new PrintWriter(errorWriter);
		scriptRunner.setErrorLogWriter(errorPrintWriter);
		// 设置读取资源文件的字符集
		Resources.setCharset(StandardCharsets.UTF_8);

		try (Reader reader = Resources.getResourceAsReader(sqlFilePath)) {
			scriptRunner.runScript(reader);
		} finally {
			try {
				connection.close();
			} catch (SQLException e) {
				logger.error("to close the connection of database is failure", e);
			}
			if (StringUtils.isNotEmpty(writer.toString())) {
				logger.info(writer.toString());
			}
			if (StringUtils.isNotEmpty(errorWriter.toString())) {
				logger.error(errorWriter.toString());
			}
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值