ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

Spring Boot——ScriptUtils.executeSqlScript执行sql脚本文件

2020-04-26 16:06:13  阅读:52  来源: 互联网

标签:String testSql Spring Boot connection executeSqlScript sql test true


背景

  • 项目测试时需要执行一些sql脚本文件,将数据初始化到数据库中

代码案例

/**
 * @author ********
 * @Description:
 * @date 2020/4/2
 */
public class ConnUtil  {
    private static final Logger logger = LoggerFactory.getLogger( ConnUtil.class );
    private Connection connection;

    public Connection executeSql( Connection connection,String sqlFileName ){

        try {
            String driverClassName = "com.mysql.cj.jdbc.Driver";
            String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&CharSet=utf8mb4&characterEncoding=utf8&characterSetResults=utf8&autoReconnect=true&autoReconnectForPools=true&rewriteBatchedStatements=true&allowMultiQueries=true&useSSL=false&serverTimezone=GMT";
            String username = "test";
            String password = "test";

            Class.forName(driverClassName);
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }

        ClassPathResource rc = new ClassPathResource(sqlFileName);
        EncodedResource er = new EncodedResource(rc, "utf-8");
        ScriptUtils.executeSqlScript(connection, er);

        return connection;
    }
//手动释放连接 void closeAll(Connection conn,PreparedStatement ps,ResultSet rs){ try { if(rs != null){ rs.close(); } if(ps != null){ ps.close(); } if(conn != null){ conn.close(); } }catch (SQLException e){ e.getMessage(); } }

  //测试
  public void testConn(){
    executeSql("testsql/test_inset_user.sql");//test_inset_user.sql存储在resources的testsql目录下
  }

}

注意

  • 使用ScriptUtils.executeSqlScript执行sql脚本文件必须手动释放连接
  • sql脚本文件需要在resources目录下
executeSql1( "testSql/test_superviser_record.sql");

executeSql2( "testSql/test_deldata.sql");
executeSql2( "testSql/test_miners.sql");
executeSql2( "testSql/test_user.sql");

标签:String,testSql,Spring,Boot,connection,executeSqlScript,sql,test,true
来源: https://www.cnblogs.com/zuiyue_jing/p/12780129.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有