Created
October 28, 2024 23:37
-
-
Save mike-seger/da81485dd66102cb9eb1d3036465064d to your computer and use it in GitHub Desktop.
Sql Script Runner for JdbcTemplate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import org.springframework.jdbc.core.JdbcTemplate | |
| import org.springframework.jdbc.support.rowset.SqlRowSet | |
| class SqlScriptRunner(private val jdbcTemplate: JdbcTemplate) { | |
| fun executeSqlScriptAndGetLastResult(sqlScript: String): SqlRowSet? { | |
| // Split script into individual statements by ";", ignoring line comments "--" and block comments "/* */" | |
| val statements = sqlScript.split("(?<!;)\\s*;\\s*(?=(?:[^']*'[^']*')*[^']*$)".toRegex()) | |
| .map { it.trim() } | |
| .filter { it.isNotEmpty() } | |
| // Execute each statement in sequence, capturing the result of the last statement only | |
| var resultSet: SqlRowSet? = null | |
| statements.forEachIndexed { index, statement -> | |
| if (index < statements.size - 1) { | |
| jdbcTemplate.execute(statement) | |
| } else { | |
| // For the last statement, use queryForRowSet to get the result | |
| resultSet = jdbcTemplate.queryForRowSet(statement) | |
| } | |
| } | |
| return resultSet // Result set from the last statement | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment