Spring Boot项目——ScriptUtils.executeSqlScript执行sql脚本文件
背景
- 项目测试时需要执行一些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");