Skip to content

Instantly share code, notes, and snippets.

@mike-seger
Created October 28, 2024 23:37
Show Gist options
  • Select an option

  • Save mike-seger/da81485dd66102cb9eb1d3036465064d to your computer and use it in GitHub Desktop.

Select an option

Save mike-seger/da81485dd66102cb9eb1d3036465064d to your computer and use it in GitHub Desktop.
Sql Script Runner for JdbcTemplate
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