栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot 调用mysql的.sql文件,执行mysql语句

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot 调用mysql的.sql文件,执行mysql语句

代码:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.init.scriptUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.sql.*;

@Component
public class ExecuteSQLUtil {
    @Value("${master.jdbc.url}")
    private String DB_URL;
    @Value("${spring.datasource.druid.username}")
    private String DB_USERNAME;
    @Value("${spring.datasource.druid.password}")
    private String DB_PWD;

    @Scheduled(cron = "0 */1 * * * ?")
    public void test (){
        executeSql("static/test1.sql");
        executeSql("static/test2.sql");
        executeSql("static/test3.sql");
        executeSql("static/test4.sql");
        executeSql("static/test5.sql");
        executeSql("static/test6.sql");
        executeSql("static/testOne.sql");
    }



    public Connection executeSql(String sqlFileName){
        Connection connection = null;
        try {
            String driverClassName = "com.mysql.cj.jdbc.Driver";
// String DB_URL = "jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=true&rewriteBatchedStatements=true";
// String DB_USERNAME = "root";
// String DB_PWD = "123456";
//            Class.forName(driverClassName);
            connection = DriverManager.getConnection(DB_URL, DB_USERNAME , DB_PWD );
        } catch (Exception e) {
            e.printStackTrace();
        }
        ClassPathResource rc = new ClassPathResource(sqlFileName);
        EncodedResource er = new EncodedResource(rc, "utf-8");
        scriptUtils.executeSqlscript(connection, er);
        return connection;
    }
}

sql文件在:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/328825.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号