Skip to content

Instantly share code, notes, and snippets.

@pedrodsa
Forked from hussachai/SqlScriptRunner.java
Last active August 26, 2016 22:20
Show Gist options
  • Save pedrodsa/d2b877e7377e097389059e65f62012a1 to your computer and use it in GitHub Desktop.
Save pedrodsa/d2b877e7377e097389059e65f62012a1 to your computer and use it in GitHub Desktop.
SQL Script Runner
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;
}
}
@pedrodsa
Copy link
Author

This fork deals with comments on the sql script

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment