-
-
Save pedrodsa/d2b877e7377e097389059e65f62012a1 to your computer and use it in GitHub Desktop.
SQL Script Runner
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 java.io.BufferedReader; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.sql.Connection; | |
import java.sql.SQLException; | |
import java.sql.Statement; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
public class SqlScriptRunner { | |
private final Logger log = LoggerFactory.getLogger(getClass()); | |
public int run(Connection conn, File file, boolean continueOnError) throws IOException { | |
return run(conn, file, "UTF-8", continueOnError); | |
} | |
public int run(Connection conn, File file, String charset, boolean continueOnError) throws IOException { | |
return run(conn, new FileInputStream(file), charset, continueOnError); | |
} | |
public int run(Connection conn, InputStream in, boolean continueOnError) throws IOException { | |
return run(conn, in, "UTF-8", continueOnError); | |
} | |
public int run(Connection conn, InputStream in, String charset, boolean continueOnError) throws IOException { | |
int success = 0; | |
BufferedReader bin = new BufferedReader(new InputStreamReader(in, charset)); | |
StringBuilder sql = new StringBuilder(); | |
String line = null; | |
boolean isInCommentBlock = false; | |
while ((line = bin.readLine()) != null) { | |
//Handle single line comments | |
if (line.trim().startsWith("//") || (line.trim().startsWith("/*") && line.trim().endsWith("*/"))) { | |
continue; | |
} | |
//Handle multiline comments | |
if (line.trim().startsWith("/*")) { | |
isInCommentBlock = true; | |
continue; | |
} | |
if (line.trim().endsWith("*/")) { | |
isInCommentBlock = false; | |
continue; | |
} | |
if (isInCommentBlock == true) { | |
continue; | |
} | |
if (line.isEmpty() == false) { | |
sql.append( '\n' + line); | |
} | |
if (line.trim().endsWith(";")) { | |
try (Statement stmt = conn.createStatement()) { | |
String str = sql.toString(); | |
log.debug("Executing SQL: \n{}", str); | |
stmt.executeUpdate(str); | |
success++; | |
} catch (SQLException e) { | |
if (continueOnError) { | |
log.error(e.getMessage(), e); | |
} else { | |
throw new RuntimeException(e); | |
} | |
} | |
sql = new StringBuilder(); | |
} | |
} | |
return success; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This fork deals with comments on the sql script