Skip to content

Instantly share code, notes, and snippets.

@witoldsz
Created January 23, 2014 22:57
Show Gist options
  • Save witoldsz/8588514 to your computer and use it in GitHub Desktop.
Save witoldsz/8588514 to your computer and use it in GitHub Desktop.
This script reads database commands from STDIN (as UTF-8), splits by semicolon, and executes command by command against given database.
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Scanner;
/**
* This script reads STDIN (as UTF-8), splits by semicolon, and executes command by command.
* Three arguments are required: database URL, username and password.
* Remember to set classpath for database driver.
* @author Witold Szczerba
*/
public class DbScriptRunner {
public static void main(String[] args) throws Exception {
String url = args[0];
String user = args[1];
String pass = args[2];
System.out.println("---> connecting '" + user + "' to " + url);
try (Connection conn = DriverManager.getConnection(url, user, pass)) {
conn.setAutoCommit(true);
try (Scanner scanner = new Scanner(System.in, "UTF-8").useDelimiter(";\\s*\n")) {
while (scanner.hasNext()) {
String command = scanner.next().trim();
if (command.isEmpty()) {
continue;
}
if (!command.endsWith(";")) {
command += ";";
}
System.out.println("cmd> " + command);
conn.createStatement().execute(command);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment