需求: 升级功能需要执行升级包中带着的.sql文件
分析; 1、获取jdbc的连接 2、获取文件路径 3、执行sql文件,异常终止
实现: 原系统中有已有实现方法,读取文件后,一行行搞,代码还多还乱,于是打算自己实现 在一顿面向bing编程后发现了ScriptUtil可以直接传入File执行,几行代码就能搞定,顿觉喜大普奔
此方法通过ScriptUtil.executeSqlScrip()传参数调用即可
ok,打完收工!提交代码,但是还没完。。。。。。
测了一轮没发现问题,可(er)爱(bi)研发经理提了要求,系统没法对用户穿上来的sql文件做要求,如果有直接Drop table,不带if exist判断的,不能认定为异常!
顿怒!在mysql中就是不对的,是执行不过的,我们用了mysql就要遵循人家的要求。。。。。巴拉巴拉
经过5分钟的据理力争,乖巧的端坐电脑前,继续查找解决办法满足变态需求!
查找无果,突然;灵光一闪:ScriptUtil是否已有此解决办法?随翻之,果然
其中有两个boolean:一是控制异常是否继续执行,二是控制是否忽略FailedDrops,完美匹配变态需求
**
* Execute the given SQL script using default settings for statement
* separators, comment delimiters, and exception handling flags.
* <p>Statement separators and comments will be removed before executing
* individual statements within the supplied script.
* <p><strong>Warning</strong>: this method does <em>not</em> release the
* provided {@link Connection}.
* @param connection the JDBC connection to use to execute the script; already
* configured and ready to use
* @param resource the resource (potentially associated with a specific encoding)
* to load the SQL script from
* @throws ScriptException if an error occurred while executing the SQL script
* @see #executeSqlScript(Connection, EncodedResource, boolean, boolean, String, String, String, String)
* @see #DEFAULT_STATEMENT_SEPARATOR
* @see #DEFAULT_COMMENT_PREFIX
* @see #DEFAULT_BLOCK_COMMENT_START_DELIMITER
* @see #DEFAULT_BLOCK_COMMENT_END_DELIMITER
* @see org.springframework.jdbc.datasource.DataSourceUtils#getConnection
* @see org.springframework.jdbc.datasource.DataSourceUtils#releaseConnection
*/
public static void executeSqlScript(Connection connection, EncodedResource resource) throws ScriptException {
executeSqlScript(connection, resource, false, false, DEFAULT_COMMENT_PREFIX, DEFAULT_STATEMENT_SEPARATOR,
DEFAULT_BLOCK_COMMENT_START_DELIMITER, DEFAULT_BLOCK_COMMENT_END_DELIMITER);
}
更换接口后测试,no problem!
打完收工,十分happy!
最后分享一首很喜欢的诗:
《自嘲》 --丁元英 本是后山人,偶做前堂客。 醉舞经阁半卷书,坐井说天阔。 大志戏功名,海斗量福祸。 待到囊中羞涩时,怒指乾坤错。