【Java】spring boot 运行sql文件

1,引入maven依赖(日志)

  		<dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
		
        <dependency>
            
            <groupId>ch.qos.logbackgroupId>
            <artifactId>logback-classicartifactId>
            <version>1.2.11version>
        dependency>

2,配置数据库连接信息

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql:///rbac?serverTimezone=UTC
    username: root
    password: root

3,编写DoSqlFile工具类

package com.manager.oa.util;

import com.manager.oa.exception.DoSqlException;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;

/**
 * @Author sms
 * @Version V1.0.0
 * @Date 2022-08-06
 * 运行SQL文件工具类
 */
@Slf4j
@Component
public class DoSqlFile {

    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;

    /**
     * 获取当前Mybatis的连接信息
     *
     * @return
     */
    public Connection getConnection() {
        log.info("【MySQL】->url:{}", url);
        log.info("【MySQL】->username:{}", username);
        log.info("【MySQL】->password:{}", password);
        Connection conn = null;
        try {
            // 建立连接
            conn = DriverManager.getConnection(url, username, password);
            log.info("数据库连接是否关闭?:{}", conn.isClosed());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }


    /**
     * 运行sql脚本
     *
     * @param sqlFilePath 执行的脚本文件
     */
    public boolean run(String sqlFilePath) {
        try {
            // 建立连接
            Connection conn = this.getConnection();
            // 创建ScriptRunner,用于执行SQL脚本
            ScriptRunner runner = new ScriptRunner(conn);
            runner.setErrorLogWriter(null);
            runner.setLogWriter(null);
            // 遇到错误回滚
            runner.setStopOnError(true);
            Resources.setCharset(Charset.forName("UTF-8"));
            // 执行SQL脚本
            runner.runScript(new InputStreamReader(new FileInputStream(sqlFilePath), "UTF-8"));
            // 关闭连接
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new DoSqlException("sql执行失败", e);
        }
        return true;
    }
}

你可能感兴趣的:(Java,java,spring,boot,sql)